Golang's errors package returns stack information
The standard library errors provide methods for handling errors. For example, commonly usedfunc New(text string) error
Use this method to handle error information and only custom output will be output.textGo to the console or log file,
There is no other auxiliary troubleshooting information output, so we can only use the regulartextGo to the global search where this error was thrown, and then locate the code-level context problem.
Of course, it's not impossible, but there are many nested codes, throwtextIf there are multiple consistent situations, it will be more troublesome. For example, the following example:
package main import ( "errors" "fmt" "os" ) func err1() error { return ("An error has been reported, an exception has been thrown!!") } func err2() error { return ("An error has been reported, an exception has been thrown!!") } func err3() error { return ("An error has been reported, an exception has been thrown!!") } func main() { err := err1() if err != nil { (err) (0) } err = err2() if err != nil { (err) (0) } err = err3() if err != nil { (err) (0) } }
Running results:
An error has been reported, an exception has been thrown! !
There are three identical error outputs in the code. According to this error message, it is impossible to determine which method it comes from. It can only be located through debugging or adding output to each err!=nil.
Here you can use third-party open source libraries:/go-errors/errors
The following is to use /go-errors/errors to modify it
package main import ( "fmt" "/go-errors/errors" "os" ) func err1() error { return nil } func err2() error { return ("An error has been reported, an exception has been thrown!!") } func err3() error { return ("An error has been reported, an exception has been thrown!!") } func main() { err := err1() if err != nil { (err.(*).ErrorStack()) (0) } err = err2() if err != nil { (err.(*).ErrorStack()) (0) } err = err3() if err != nil { (err.(*).ErrorStack()) (0) } }
Running results:
* An error has been reported, an exception has been thrown! !
D:/gotest/src/test/:14 (0x49756b)
main: return ("An error has been reported, an exception has been thrown!!")
D:/gotest/src/test/:27 (0x497559)
main: err = err2()
D:/golang/src/runtime/:250 (0x4379fe)
main: fn()
D:/golang/src/runtime/asm_amd64.s:1594 (0x45ee41)
goexit: BYTE $0x90 // NOP
With call stack information, you know very clearlyerr2()There is a problem. This library records the call stack,ErrorStack method returns call stack information
The above is the detailed content of using errors to return call stack information in Golang. For more information about Golang errors to return stack information, please pay attention to my other related articles!