Use panic and recover to simplify error handling in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

With the use of Golang more and more frequent, found that Golang has a place is very inconvenient, is in error handling. Let's take a look at the usual error handling methods in Golang:

The usual error handling

123456789101112131415161718 packagemainimport (    "errors"    "fmt")func a() (err error) {    err = errors.New("错误")    return}func main() {    err := a()    iferr != nil {        fmt.Println(err)    }}

The function adds the return value of the error type when it returns, and if there is an error, it is assigned to err, and the err is judged at the calling function, and the error is handled if it is not nil. This way in the nesting layer when the time is good to do, if the nesting of more layers that will be a first-level return to err, obviously will be very troublesome. As in the following code:

123456789101112131415161718192021222324252627282930313233343536 packagemainimport (    "errors"    "fmt") func a() (err error) {    err = b()    iferr != nil {        return    }    err = c()    iferr != nil {        return    }    err = errors.New("a内错误")    return}func b() (err error) {    err = errors.New("b内错误")    return}func c() (err error) {    err = errors.New("c内错误")    return}func main() {    err := a()    iferr != nil {        fmt.Println(err)    }}

A function called the B and C functions, after the call to make err! = Nil judgment, if another D method, E method, that would not be very troublesome. In the actual development time, this multi-layer nesting also often exist, such as user registration function to judge a lot of things: the form validation is OK, whether the user already exists, whether the data is inserted OK and so on.

Try to use the panic

So I think there is no way to be more convenient, at least not to call each function to judge the next Err!=nil, so you can omit three lines of code. Knowing that the panic method in Golang can interrupt the process directly, it feels like a solution should be found along the way. Understand the detailed use of the next panic, in fact, is also very simple, that is panic, if you need to catch this panic error, in the peripheral method in advance to declare the recover method. Look at the code:

12345678910111213141516171819 packagemainimport (    "log")func main() {    deferfunc() {        ifr := recover(); r != nil {            log.Printf("Runtime error caught: %v", r)        }    }()    a()}func a() {    panic("a内错误")}

An error is thrown inside a function, which is recover by the defer function in the periphery, and then the error can be processed. Use this method to change the code above with err processing.

12345678910111213141516171819202122232425262728293031 packagemainimport (    "log")func a() {    b()    c()    panic("a内错误")    return}func b() {    panic("b内错误")}func c() (err error) {    panic("c内错误")}func main() {    deferfunc() {        ifr := recover(); r != nil {            log.Printf("Runtime error caught: %v", r)        }    }()    a()}

Can see the whole code is a lot of concise, of course, the code here is relatively simple may not see much effect, in the business is more complex, often to do a variety of checks when you can show a concise.

In the development of API interface project, I will encapsulate the recover method to handle the internal return of the error message, and then unified output to the client, feel much more convenient.

Reprint Please specify: Happy programming»golang to do business process interruption with panic and recover

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.