...

/

Handling Errors in Go

Handling Errors in Go

Understand how to create and use errors in Go.

Many of us come from languages that handle errors using exceptions. Go takes a different approach, treating errors like our other data types. This prevents common problems that exception-based models have, such as exceptions escaping up the stack.

Go has a built-in error type called error. It is based on the interface type, with the following definition:

Press + to interact
type error interface {
Error() string
}

Now, let's look at how we can create an error.

Creating an error

The most common way to create errors is using either the errors package's New() method or the fmt package's Errorf() method. Use errors.New() when we don't need to do variable substitution and fmt.Errorf() when we do. We can see both methods in the following code snippet:

Press + to interact
err := errors.New("this is an error")
err := fmt.Errorf("user %s had an error: %s", user, msg)
...