Error handling
In Go Errors are values just like any other return value from a function. There NOT considered exceptional, we can expect them right?
For example, the following code used to open a file returns two values, the second being the values of a potential error:
We consider error handling immediately, and deal with them as soon as they might occur.
This simplifies code review and understanding, this pattern is one of the reasons Go is considered a stable and production ready language.
Mechanics
Don't just check errors, handle them gracefully.
To be an error in go you have a method called Error which returns a string. The error is of the built in type interface.
You can create your own errors:
package main
import (
"errors"
"fmt"
)
func main() {
err := errors.New("this is an error message")
fmt.Println(err)
err2 := fmt.Errorf("this error wraps the first one: %w", err)
fmt.Println(err2)
}
With these features, we can always handle errors in function, checking and returning an error should one arise.
package main
import (
"errors"
"fmt"
"log"
)
func main() {
message, err := Message("")
if err != nil {
log.Fatal(err)
}
fmt.Println(message)
}
func Message(name string) (string, error) {
if name == "" {
return "", errors.New("empty name")
}
message := fmt.Sprintf("Hi, %v. Welcome!", name)
return message, nil
}