Golang : Error handling methods




Couple of days ago I attended a Golang meetup for the first time nearby where I live. There are developers coming from different backgrounds, some from C, Python, Java and NodeJS looking to know more about Golang.

One of the topics we talked about in the meetup is Golang's error handling. Many Java developers that used to exception handling were surprised why Golang did not classified the error type and provide a mechanism to catch the error. The error handling topic sparked a debate on the merit of having something similar in Golang....but since none of us is in the Golang core developer group so we will leave it there.

While Golang did not provide a way to determine the type of error(probably stack trace is just too confusing and time wasting ?? ) or handle error in a elegant way(this is something that sparked the debate).

Basically, there are "3 standard ways" of dealing with errors in Go :

 if err != nil {
 //deal with err
 }

or

 value, err := aFunction()

 if err != nil {
 //deal with err
 }
 // no error, proceed to deal with value

and

 if _, err := f.Read(file); err != nil {
 //deal with err
 }
 // no error, process f further

Golang has the defer, panic and recover way of dealing with error, but sometimes it can be overkill for developer looking to print out own stack trace information for debugging purpose or simply want to deal with the error on the spot and not having the program exiting.

If you prefer not to use the defer, panic and recover method, you can use the strings.Contains() to catch specific words in the error message.

For example :

  if !strings.Contains(err.Error(), "timed out") {
 fmt.Printf("resulting error not a timeout: %s", err)
  }

or

  if strings.Contains(err.Error(), "open error") {
 // Do something to recover from the file open error
 // such as prompt the user to enter a valid filename instead of exiting and start 
 // all over again.
  }

For more information about error handling, please visit http://blog.golang.org/error-handling-and-go

Hope these error handling methods can be useful in your coding journey with Golang.





By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


Advertisement