typestar

A custom error type in Go

A struct error carries data, and can decide what it matches.

type HTTPError struct {
    Status int
    Cause  error
}

func (e *HTTPError) Error() string {
    return fmt.Sprintf("http %d: %v", e.Status, e.Cause)
}

func (e *HTTPError) Unwrap() error { return e.Cause }

func (e *HTTPError) Is(target error) bool {
    return target == ErrServerSide && e.Status >= 500
}

var ErrServerSide = errors.New("server side")

func classify(status int) bool {
    err := &HTTPError{Status: status, Cause: errors.New("boom")}
    return errors.Is(err, ErrServerSide)
}

How it works

  1. Error() on a pointer receiver is the usual choice.
  2. Unwrap exposes an inner error to Is and As.
  3. Adding an Is method lets one error match a category.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
475
Tokens
121
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 1 of 2 in Your own errors, step 8 of 15 in Errors.

← Previous Next →