Error handling has been a very controversial area of Go, and people have contributed all sorts of ideas to proposals in that category. Recently, I also found an interesting technical proposal: the left-hand side function; and a new idea for Go+.
Go’s new proposal: the left-hand side function
With the existing Go1 error handling mechanism, we generally need to write a lot of if err ! = nil logic.
Some people laughingly claim that 50 out of 100 lines of code are the following.
So several people in the community came up with the idea of left-handed functions.
We hope to solve the error handling problem by reducing the extra 3 lines of code written each time and achieving a consistent error handling method.
The following proposal was involved.
- proposal: Go 2: errors: allow function on left hand side of assignment
- proposal: Alternate to try(): 1. Call func/closure from assignment and 2. break/continue/return more than one level
The new code in the proposal is as follows.
|
|
Simplified writing.
|
|
A new way of thinking about handling errors is to add a layer (the universal software architecture way of handling them) and use the left-hand function to handle all errors.
Go+: Error Expressions
A member of the Go-related group: Go+, has also made its own “ErrWrap expressions” error handling solution, which was discussed by a certain number of people in the previous proposal, so you can evaluate it together.
Introduction to expressions
The core idea is to add a syntactic mechanism of expressions to error handling. As follows.
We’ll expand on them one by one.
The expression expr! checks if valN is zero. If not, it will panic. the corresponding Go code.
The expression expr? checks if valN is nil, and if not, it returns an error. Corresponding Go code.
The expression expr?:defval checks if valN is nil. if not, it uses defval as the value of expr. Corresponding Go code.
Demonstration code
Specific sample code.
|
|
Output.
In addition to the optimization of the mechanism for error handling based on expressions, information tracking of the error stack has been added.