Handling errors in Go
Many of you will come from languages that handle errors using exceptions. Go took 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
. error
is based on the interface
type, with the following definition:
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 you don't need to do variable substitution and fmt.Errorf()
when you do. You can see both methods in the following code snippet:
err := errors.New("this is an error") err := fmt.Errorf("user %s had an error: %s", user, msg)
In both the preceding examples, err
will be of...