Exception Handling for Golang

Source: Internet
Author: User
Tags gopher

Exception Handling for Golang

Image

GolangThe 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
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.