Home >Backend Development >Golang >How to handle errors in golang
Golang usually has three error handling methods: error sentinel (Sentinel Error), error type assertion and recording error call stack. The error sentinel refers to using a variable with a specific value as the judgment condition for the error processing branch. Error types are used to route error handling logic and have the same effect as error sentries. The type system provides uniqueness of error types. The error black box refers to not caring too much about the error type and returning the error to the upper layer; when action needs to be taken, assertions must be made about the error behavior rather than the error type.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
Golang does not provide try-catch
similar error handling mechanism. It adopts C language style error handling at the design level and returns error information through function return values. The specific examples are as follows :
func ReturnError() (string, error) { return "", fmt.Errorf("Test Error") } func main() { val, err := ReturnError() if err != nil { panic(err) } fmt.Println(val) }
The above example is a basic error handling example. The call stack executed in a production environment is often very complex, and the returned error
is also varied. It is often necessary to return The error message determines the specific error handling logic.
Golang usually has the following three error handling methods, error sentinel (Sentinel Error), error type assertion (Error Type Asseration) and recording error call stack.
Sentinel refers to using a variable with a specific value as the judgment condition of the error processing branch. Common application scenarios include # in gorm. ##gorm.RecordNotFounded and
redis.NIL in the redis library.
error type variable points to the same address, the two variables are equal, otherwise they are not equal.
var ErrTest = errors.New("Test Error") err := doSomething() if err == ErrTest{ // TODO: Do With Error }There are the following problems when using Sentinel. There are two problems: 1. The code structure is not flexible, and branch processing can only use
== or
! = Make a judgment. If things go on like this, it is easy to write spaghetti-like code.
var ErrTest1 = errors.New("ErrTest1") var ErrTest2 = errors.New("ErrTest1") var ErrTest3 = errors.New("ErrTest1") …… var ErrTestN = errors.New("ErrTestN") …… if err == ErrTest1{ …… } else if err == ErrTest2{ …… }else if err == ErrTest3{ …… } …… else err == ErrTestN{ …… }2. The value of the sentinel variable cannot be modified, otherwise it will cause a logic error. The error sentinel in the above golang writing method can be changed, which can be solved in the following ways:
type Error string func (e Error) Error() string { return string(e) }3. The sentinel variable will This leads to extremely strong coupling, and the spitting out of new errors in the interface will cause users to modify the code accordingly and create new processing errors. Compared with the above solution, Error Sentinel has a more elegant solution that relies on interfaces instead of variables:
var ErrTest1 = errors.New("ErrTest1") func IsErrTest1(err error) bool{ return err == ErrTest1 }
type TestError { } func(err *TestError) Error() string{ return "Test Error" } if err, ok := err.(TestError); ok { //TODO 错误分支处理 } err := something() switch err := err.(type) { case nil: // call succeeded, nothing to do case *TestError: fmt.Println("error occurred on line:", err.Line) default: // unknown error }Compared with sentinels, the immutability of error types changes Good, and
switch can be used to provide elegant routing strategies. But this makes it impossible for users to avoid excessive dependence on packages.
func fn() error{ x, err := Foo() if err != nil { return err } } func main(){ err := fn() if IsTemporary(err){ fmt.Println("Temporary Error") } } type temporary interface { Temporary() bool } // IsTemporary returns true if err is temporary. func IsTemporary(err error) bool { te, ok := err.(temporary) return ok && te.Temporary() }In this way, 1. Dependencies between interfaces are directly decoupled, 2. Error handling routing has nothing to do with error types, but is related to specific behaviors, avoiding the expansion of error types.
Black box processing, returning an error does not mean ignoring the existence of the error or directly ignoring it, but it needs to be handled gracefully in the appropriate place. In this process, you can use errorsWrap,
Zaplogging, etc. to record the context information of the calling link as errors are returned layer by layer. .
func authenticate() error{ return fmt.Errorf("authenticate") } func AuthenticateRequest() error { err := authenticate() // OR logger.Info("authenticate fail %v", err) if err != nil { return errors.Wrap(err, "AuthenticateRequest") } return nil } func main(){ err := AuthenticateRequest() fmt.Printf("%+v\n", err) fmt.Println("##########") fmt.Printf("%v\n", errors.Cause(err)) } // 打印信息 authenticate AuthenticateRequest main.AuthenticateRequest /Users/hekangle/MyPersonProject/go-pattern/main.go:17 main.main /Users/hekangle/MyPersonProject/go-pattern/main.go:23 runtime.main /usr/local/Cellar/go@1.13/1.13.12/libexec/src/runtime/proc.go:203 runtime.goexit /usr/local/Cellar/go@1.13/1.13.12/libexec/src/runtime/asm_amd64.s:1357 ########## authenticate【Related recommendations:
Go video tutorial, Programming teaching】
The above is the detailed content of How to handle errors in golang. For more information, please follow other related articles on the PHP Chinese website!