errors

The library’s errors implementation is relatively simple and cannot be traced back to the stack. It is not very friendly to the upper level caller when the error was generated. You cannot get the call chain details of the error.

// No stack err := errors.New("error MSG ") fmt.Printf("%+v\n", errCopy the code

pkg/errors

github.com/pkg/errors supports stack information to get error call chain details.

ordinary

Err := errors.New("error MSG ") ftt. Printf("%+v\n", Err) / / output error MSG main. The main/Users/xinliang/go/project/demo/err, err... go: 14 runtime. The main /usr/local/go/src/runtime/proc.go:225 runtime.goexit /usr/local/go/src/runtime/asm_amd64.s:1371Copy the code

With stack, packaging description

Err := errors.Wrap(err Error, message String) or err := errors.Wrapf(err Error, format String, args... interface{})Copy the code

With stack, not wrapped description

err := errors.WithStack(err error)
Copy the code

No stack, package description

Err := errors.WithMessage(err Error, message String) or err := errors.WithMessagef(err Error, format String, args... interface{})Copy the code

thinking

What are the problems we encounter when using PKG /errors?

Will encounter the problem of duplicate stack!

For example, if a method has a long call link, this can happen, for example:

func main() {
	err := func1()
	fmt.Printf("%+v\n", errors.Wrapf(err, "func1 error occurred"))
}

func func1() error {
	err := func2()
	return errors.Wrapf(err, "func2 error occurred")
}

func func2() error {
	err := errors.New("error msg")
	return err
}
Copy the code

Think about it. What would it print?

Did you find any duplicates in the printed stack?

How to solve this problem? Come and talk on my planet.