go error

作者: 真大熊 | 来源:发表于2020-10-29 10:24 被阅读0次

1.why shoud we wrap go error

var ErrPermission = errors.New("permission denied")
// DoSomething returns an error wrapping ErrPermission if the user
// does not have permission to do something.
func DoSomething() {
    if !userHasPermission() {
        // If we return ErrPermission directly, callers might come
        // to depend on the exact error value, writing code like this:
        //
        //    if err := pkg.DoSomething(); err == pkg.ErrPermission { … }
        //
        // This will cause problems if we want to add additional
        // context to the error in the future. To avoid this, we
        // return an error wrapping the sentinel so that users must
        // always unwrap it:
        //
        //    if err := pkg.DoSomething(); errors.Is(err, pkg.ErrPermission) { ... }
        return fmt.Errorf("%w", ErrPermission)
    }
    // ...
}

2.usage

var brokenErr = errors.New("I'am broken!")
// ...
err4 := fmt.Errorf("some %v wrong: %w", "james", brokenErr)
    fmt.Println(err4.Error())
    fmt.Println(errors.Unwrap(err4).Error())
    // value equal 
    fmt.Println("is: ", errors.Is(err4, brokenErr))
    // type assert,  second param must pointer or interface. use &.
    fmt.Println("as: ", errors.As(err4, &brokenErr))

3.details

  • errors.Is will recursive all errors wraped in the error, if any one is equal then return true.
  • errors.As also recursive the errors wraped, if find the first type match then return true, else return nil.
  • we use [Is] to check if the internal error is some thing.
  • we use [As] to handle all the specific type errors.

相关文章

  • 2021/05/04关于GO的错误处理(error)

    1.首先何谓error GO中的error就是一个普通的接口(实现了Error方法) 位于源码builtin.go...

  • 第05天(异常、文本文件处理)_01

    01_error接口的使用.go 02_error接口应用.go 03_显式调用panic函数.go 04_数组越...

  • 《Go源码解读篇》之 Error

    Go 语言中必不可少的类型 --- error,Go 中的原生代码少,而且易掌握. What is error? ...

  • go error处理

    背景介绍 如果你有写过Go代码,那么你可以会遇到Go中内建类型error。Go语言使用error值来显示异常状态。...

  • 报错:go run: cannot run *_test.go

    ERROR:go run: cannot run *_test.go files 比如执行:go run aaa_...

  • Go 基础 3:error handling

    官网: https://blog.golang.org/error-handling-and-go error对于...

  • Golang实践-error

    Golang实践-error Error Go error 是一个普通的接口,普通的值 经常使用errors.Ne...

  • 基础-3

    异常处理 error接口:Go中的一个关于错误处理的标准模式,属于Go内建的接口类型;type error int...

  • Go error

    error Go 使用 error 类型来表示函数执行过程中遇到的错误,如果返回的 error 值为 nil,则表...

  • go error

    1.why shoud we wrap go error 2.usage 3.details errors.Is ...

网友评论

      本文标题:go error

      本文链接:https://www.haomeiwen.com/subject/qekkvktx.html