Many languages use exceptions and try/catch blocks to handle errors.
Go does not. In Go, errors are just values.
Go has a built-in type called error.
A function that can fail returns an error as its last return value.
If nothing went wrong, the error is nil.
There are two common ways to create an error:
↳ 1) errors.New
import "errors"
err := errors.New("something went wrong")This creates a simple error with a message.
↳ 2) fmt.Errorf
import "fmt"
name := "config.yaml"
err := fmt.Errorf("file not found: %s", name)This creates an error with formatted text, just like fmt.Sprintf.
There are some error declarations in main.go file.
But they are incomplete.
Open main.go file and complete the code lines.
Then validate your code by running:
go run topic.go 41 validate✅ If everything is ok, you should see:
OK!
Now you know what errors are in Go.
Continue to the next topic 👇
