error handling in go

[TOC]

参考:

  • https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully

引入

在go中,所有的异常实现了 error 接口,在go中必须强制处理每层的error。error 接口如下:

type error interface {
    Error() string
}

创建error

有以下几种方式:

  • error.New()
  • fmt.Errorf(format, ...var)
  • custom error
// 第一种
// CustomError is a struct that will implement
// the Error() interface
type CustomError struct {
    Result string
}
func (c CustomError) Error() string {
    return fmt.Sprintf("there was an error; %s was the result", c.Result)
}
// 第二种方式
// TypedError is a way to make an error type
type TypedError struct {
    error
}
err := TypedError{errors.New("this is a error")}

error 的使用

  • err.(type) == TypedError
  • err == ErrorValue

pkg/errors

wrap

  • erros.New("error massage")
  • errors.Wrap(err, "the error prefix message")
  • errors.Wrap(ErrorTyped{"type error"}, "prefix")
  • 打印堆栈: fmt.Printf("%+v", err)

unwrap and type assertion

// we can handle many error types
switch errors.Cause(err).(type) {
case ErrorTyped:
    fmt.Println("a typed error occurred: ", err)
default:
    fmt.Println("an unknown error occurred")
}

你可能感兴趣的:(error handling in go)