Exception Handling for Golang
Image
Golang
The advantages of a lot of previous articles have also been mentioned, but there are many slots for Gopher, especially 错误处理
.
Before you say a mistake or an exception, you should say two concepts:
error Handling : Errors are part of the business and can be foreseen.
exception Handling : Non-business part, unforeseeable.
Error handling
First look at the sample code:
file, err := os.Open("/usr/local/test.txt")
Golang officially recommends error handling in the above code, and it is recommended to err
put it at the end of the return value. We also need to follow such rules to define in our daily coding func
.
There's a joke circulating between Gopher: Half the time you write code, and half the time you write error handling.
Example code:
func Open(name string) (*File, error) { return OpenFile(name, O_RDONLY, 0)}
But usually not every method needs to be processed err
, you can properly err
return to the upper function, the upper function uniformly printing or processing errors. For example http
, an error in a route can be processed before the route returns data, and the error message and error code are formatted and returned to Client
.
Exception handling
Golang exception Handling is a maverick, need to defer
err
recover()
use three, and Java as long as try{ }Catch()
it can be done, or look at the sample code:
package mainimport ( "fmt")func main() { test()}func test() { defer func() { if e := recover(); e != nil { fmt.Println("Worng!") } }() panic("panic")}
test()
If a panic error occurs in the function and its child functions, the code will print:
Worng!
Code Encapsulation
Of course, it is not elegant to write such a large stack of redundant code at the top of each method, and it does not conform to the object-oriented nature: 封装
so it can be encapsulated CoverErrorMessage()
, and the test()
function is rewritten as follows:
package mainimport ( "fmt")func main() { test()}func test() { defer tools.CoverErrorMessage() panic("panic")}func CoverErrorMessage() { if message := recover(); message != nil { var err error switch x := message.(type) { case string: err = errors.New(x) case error: err = x default: err = errors.New("Unknow panic") } Logger.Error("Recovered panic error : ",err) }}
Defer can only recover()
write in the first layer function when handling exceptions, otherwise it will not be able recover()
to panic error
Image