How to handle errors in golang

青灯夜游
Release: 2022-12-26 17:44:42
Original
5829 people have browsed it

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.

How to handle errors in golang

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)
}
Copy after login

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.

Error Sentinel (Sentinel Error)

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.

Golang can compare variables of the same type, and interface variables compare the addresses of pointers pointed to by the interface. Therefore, if and only if the

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
}
Copy after login

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{
	……
}
Copy after login

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) }
Copy after login

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
}
Copy after login

Error type

Error types are used to route error processing logic, which has the same effect as error sentries. The type system provides the uniqueness of error types. The usage method is as follows:

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
}
Copy after login

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.

Using the interface to throw more complex and diverse errors still requires changing the caller's code.

Error black box (depends on error interface)

Error black box refers to not paying too much attention to the error type and returning the error to the upper layer. When action is required, make assertions about the behavior of the error, not the type of error.

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()
}
Copy after login

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.

Summary

Error sentinels and error types cannot avoid the problem of excessive dependence. Only the error black box can change the problem from the processing logic of determining the error type (variable) to To determine wrongdoing. Therefore it is recommended to use the third way to handle errors.

It is necessary to add one sentence here,

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
Copy after login
【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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template