Creating Custom Errors in Go

Written by Gopher Guides

Go provides two methods to create errors in the standard library, errors.New and fmt.Errorf. When communicating more complicated error information to your users, or to your future self when debugging, sometimes these two mechanisms are not enough to adequately capture and report what has happened. To convey this more complex error information and attain more functionality, we can implement the standard library interface type, error.

The syntax for this would be as follows:

  1. type error interface {
  2. Error() string
  3. }

The builtin package defines error as an interface with a single Error() method that returns an error message as a string. By implementing this method, we can transform any type we define into an error of our own.

Let’s try running the following example to see an implementation of the error interface:

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. type MyError struct{}
  7. func (m *MyError) Error() string {
  8. return "boom"
  9. }
  10. func sayHello() (string, error) {
  11. return "", &MyError{}
  12. }
  13. func main() {
  14. s, err := sayHello()
  15. if err != nil {
  16. fmt.Println("unexpected error: err:", err)
  17. os.Exit(1)
  18. }
  19. fmt.Println("The string:", s)
  20. }

We’ll see the following output:

Output

  1. unexpected error: err: boom
  2. exit status 1

Here we’ve created a new empty struct type, MyError, and defined the Error() method on it. The Error() method returns the string "boom".

Within main(), we call the function sayHello that returns an empty string and a new instance of MyError. Since sayHello will always return an error, the fmt.Println invocation within the body of the if statement in main() will always execute. We then use fmt.Println to print the short prefix string "unexpected error:" along with the instance of MyError held within the err variable.

Notice that we don’t have to directly call Error(), since the fmt package is able to automatically detect that this is an implementation of error. It calls Error() transparently) to get the string "boom" and concatenates it with the prefix string "unexpected error: err:".

Collecting Detailed Information in a Custom Error

Sometimes a custom error is the cleanest way to capture detailed error information. For example, let’s say we want to capture the status code for errors produced by an HTTP request; run the following program to see an implementation of error that allows us to cleanly capture that information:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. )
  7. type RequestError struct {
  8. StatusCode int
  9. Err error
  10. }
  11. func (r *RequestError) Error() string {
  12. return fmt.Sprintf("status %d: err %v", r.StatusCode, r.Err)
  13. }
  14. func doRequest() error {
  15. return &RequestError{
  16. StatusCode: 503,
  17. Err: errors.New("unavailable"),
  18. }
  19. }
  20. func main() {
  21. err := doRequest()
  22. if err != nil {
  23. fmt.Println(err)
  24. os.Exit(1)
  25. }
  26. fmt.Println("success!")
  27. }

We will see the following output:

Output

  1. status 503: err unavailable
  2. exit status 1

In this example, we create a new instance of RequestError and provide the status code and an error using the errors.New function from the standard library. We then print this using fmt.Println as in previous examples.

Within the Error() method of RequestError, we use the fmt.Sprintf function to construct a string using the information provided when the error was created.

Type Assertions and Custom Errors

The error interface exposes only one method, but we may need to access the other methods of error implementations to handle an error properly. For example, we may have several custom implementations of error that are temporary and can be retried—denoted by the presence of a Temporary() method.

Interfaces provide a narrow view into the wider set of methods provided by types, so we must use a type assertion to change the methods that view is displaying, or to remove it entirely.

The following example augments the RequestError shown previously to have a Temporary() method which will indicate whether or not callers should retry the request:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. )
  8. type RequestError struct {
  9. StatusCode int
  10. Err error
  11. }
  12. func (r *RequestError) Error() string {
  13. return r.Err.Error()
  14. }
  15. func (r *RequestError) Temporary() bool {
  16. return r.StatusCode == http.StatusServiceUnavailable // 503
  17. }
  18. func doRequest() error {
  19. return &RequestError{
  20. StatusCode: 503,
  21. Err: errors.New("unavailable"),
  22. }
  23. }
  24. func main() {
  25. err := doRequest()
  26. if err != nil {
  27. fmt.Println(err)
  28. re, ok := err.(*RequestError)
  29. if ok {
  30. if re.Temporary() {
  31. fmt.Println("This request can be tried again")
  32. } else {
  33. fmt.Println("This request cannot be tried again")
  34. }
  35. }
  36. os.Exit(1)
  37. }
  38. fmt.Println("success!")
  39. }

We will see the following output:

Output

  1. unavailable
  2. This request can be tried again
  3. exit status 1

Within main(), we call doRequest() which returns an error interface to us. We first print the error message returned by the Error() method. Next, we attempt to expose all methods from RequestError by using the type assertion re, ok := err.(*RequestError). If the type assertion succeeded, we then use the Temporary() method to see if this error is a temporary error. Since the StatusCode set by doRequest() is 503, which matches http.StatusServiceUnavailable, this returns true and causes "This request can be tried again" to be printed. In practice, we would instead make another request rather than printing a message.

Wrapping Errors

Commonly, an error will be generated from something outside of your program such as: a database, a network connection, etc. The error messages provided from these errors don’t help anyone find the origin of the error. Wrapping errors with extra information at the beginning of an error message would provide some needed context for successful debugging.

The following example demonstrates how we can attach some contextual information to an otherwise cryptic error returned from some other function:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type WrappedError struct {
  7. Context string
  8. Err error
  9. }
  10. func (w *WrappedError) Error() string {
  11. return fmt.Sprintf("%s: %v", w.Context, w.Err)
  12. }
  13. func Wrap(err error, info string) *WrappedError {
  14. return &WrappedError{
  15. Context: info,
  16. Err: err,
  17. }
  18. }
  19. func main() {
  20. err := errors.New("boom!")
  21. err = Wrap(err, "main")
  22. fmt.Println(err)
  23. }

We will see the following output:

Output

  1. main: boom!

WrappedError is a struct with two fields: a context message as a string, and an error that this WrappedError is providing more information about. When the Error() method is invoked, we again use fmt.Sprintf to print the context message, then the error (fmt.Sprintf knows to implicitly call the Error() method as well).

Within main(), we create an error using errors.New, and then we wrap that error using the Wrap function we defined. This allows us to indicate that this error was generated in "main". Also, since our WrappedError is also an error, we could wrap other WrappedErrors—this would allow us to see a chain to help us track down the source of the error. With a little help from the standard library, we can even embed complete stack traces in our errors.

Conclusion

Since the error interface is only a single method, we’ve seen that we have great flexibility in providing different types of errors for different situations. This can encompass everything from communicating multiple pieces of information as part of an error all the way to implementing exponential backoff. While the error handling mechanisms in Go might on the surface seem simplistic, we can achieve quite rich handling using these custom errors to handle both common and uncommon situations.

Go has another mechanism to communicate unexpected behavior, panics. In our next article in the error handling series, we will examine panics—what they are and how to handle them.