If Go is not your first language, error handling in Go seems too verbose and repetitive
It’s like hitting the gym for the first time, it will break you and you either never go back or you push through and build muscle.
The happy path
One of the key shifts for me was, happy path programming, where you write a program imagining the happy path / what is supposed to happen
If everything goes correctly, then you start handling the errors and throw exceptions.
Go wants you to handle the error there itself, unlike Python when every indentation may take you deep into happy path and later you can go back and define the exceptions and error cases, go prevents it since you can’t proceed without handling the error.
At first this seems too much upfront work, and there are cases where it is difficult to decide what error to return.
Ex – In case of nested functions, do you even need to propagate the innermost function error to the top level function or should you be returning a new error at each level
Let’s shift focus for a minute, let’s dive into some features of error handling in Go
Go has a data type for an error
You can define a custom error function for you package / struct that will get called automatically when something goes wrong and you have control over your error messages.
package main
import (
"fmt"
"play.ground/isNameSudopowerCheck"
)
func main() {
x := isNameSudopowerCheck.IsNameSudopowerCheck{Name: "Sudopowers"}
err := x.CheckName()
if err != nil {
fmt.Printf("name is incorrect: %s | err:[%v]\n", x.Name, err)
return
}
fmt.Printf("name is correct: %s | err: [ %v ]\n", x.Name, err)
}
-- go.mod --
module play.ground
-- isNameSudopowerCheck/main.go --
package isNameSudopowerCheck
type IsNameSudopowerCheck struct {
Name string
}
func (x *IsNameSudopowerCheck) Error() string {
return "name is not Sudopower"
}
func (x *IsNameSudopowerCheck) CheckName() error {
if x.Name != "Sudopower" {
return &IsNameSudopowerCheck{}
}
return nil
}
name is incorrect: Sudopowers | err:[name is not Sudopower]
OR
name is correct: Sudopower | err: [ <nil> ]
If you look at line #33 & #35 you can see CheckName is defined to return type error but returns an instance of the struct itself.
This is because we satisfy the error data type by satisfying it’s interface by defining it’s required methods
Our struct must implement the Error function to return it as type error. This is the power of interfaces in Go and error type showcases this beautifully.
if err!=nil
I will write more about go errors soon…
Leave a Reply