How to Handling Error in go?
Error handling is critical in any program you write or in any programming language you use.
When it come in Golang there is some unique way to handling error. But if you not carefully handling them they will punch you in the face.
So most of the programming language have feature called Exception to handling an error.
But in Go there's no exception instead we only have error type. No try catch block to handle an error, instead we just check if the function that we called returning an error.
So here's an example error handling in go.
func CallExternalService() interface{}, error {
return nil, fmt.Errorf("some error returned from here")
}
Now if you call the function this way it will crash you application if the function returning an error.
func main() {
res, err := CallExternalService()
sentResponse(res)
}
In Go there's a nil
which is a feature that will crash your program if you not using it correctly.
In this case because the function CallExternalService
returning an error the variable res
is nil, so when we send those variable to other function it will crash your program when that sentResponse
function accessing the res
value because it nil.
So to handle this error you will need to do it like this.
func main() {
res, err := CallExternalService()
if err != nil {
// stop the process here
// it will crash if we keep go to the next instruction
}
}
Or you also can do it one line like this.
func main() {
if res, err := CallExternalService(); err != nil {
// stop the program
}
}
I highly recommend you take a look at this article from Jesse Duffield about error handling in Go.
Basically error handling in Go it just if statement everywhere!
Finding Unhandled Error
At my current company I work with legacy code a lot. And often I got this minor bug but serious bug because it will kill you app when you not handling your error.
While the Golang compiler it self doesn't help us with this kind of issue when we forget to handler an error from function call.
So I have this simple command line application I called it err-lint that can helping you finding an unhandled error in your go project.
Here's an example how you can use it.
Panic Recovery
One thing that will causing panic in Go program is when we accessing nil value or out of bound array index.
Nil value :
package main
import "fmt"
type Data struct {
key string
}
func getData() *Data {
return nil
}
func main() {
var data = getData()
fmt.Printf("%s\n", data.key)
}
So to recover from this disaster we can do it like this.
package main
import "fmt"
type Data struct {
key string
}
func getData() *Data {
return nil
}
func accessData() {
var data = getData()
fmt.Printf("%s\n", data.key)
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
accessData()
}