Golang attempts to disrupt business processes with panic and recover

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

package main import (    "errors"    "fmt") func a() (err error) {    err = errors.New("错误")    return} func main() {    err := a()    if err != 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:

package main import (    "errors"    "fmt") func a() (err error) {    err = b()    if err != nil {        return    }    err = c()    if err != 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()    if err != 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:

package main import (    "log") func main() {    defer func() {        if r := 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.

package main import (    "log") func a() {    b()    c()     panic("a内错误")    return} func b() {    panic("b内错误")} func c() (err error) {    panic("c内错误")} func main() {    defer func() {        if r := 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.

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.