liveBook · Manning

Errors.As

As explained in Learn Go with Pocket-Sized Projects

errors.As is a Go function that finds an error assignable to a target type and stores it through the supplied target pointer.

errors.As finds an error assignable to a target type and reports whether the match succeeded. When it succeeds, it stores the matching error through the supplied target pointer. section 6.6.2

Use errors.As when the matching error's type exposes information needed for the next decision:

  • Declare a variable with the desired error type, then pass its address to errors.As. For a *url.Error target, this produces a pointer to a pointer. section 6.6.2
  • Check the returned Boolean before using the populated target. section 6.6.2
  • Inspect type-specific fields or methods after a successful match, such as url.Error.Timeout(). section 6.6.2
  • Translate a matched domain error into an API response, such as mapping InvalidInputError to codes.InvalidArgument. section 10.3.2

Detecting an HTTP timeout

resp, err := c.client.Get(path) if err != nil { var urlErr *url.Error if ok := errors.As(err, &urlErr); ok && urlErr.Timeout() { // This is a timeout! } }

Mapping invalid input at a gRPC boundary

got, err := habit.Create(ctx, h) if err != nil { var invalidErr habit.InvalidInputError if errors.As(err, &invalidErr) { return nil, status.Error(codes.InvalidArgument, invalidErr.Error()) } return nil, status.Errorf(codes.Internal, "cannot save habit %v: %s", h, err.Error()) }

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains the Boolean result, target population, and pointer-to-pointer requirement, then applies type-specific methods and API mapping.
Examples
Demonstrates HTTP timeout detection and InvalidInputError translation in a gRPC CreateHabit endpoint.
What it assumes
Assumes Go error handling, pointers, HTTP clients, and gRPC endpoints; clarifies pointer targets through comparison with decoding APIs.
What you can do after
Diagnose typed failures and route them to timeout handling or precise gRPC status responses.
How it connects
Connects error classification with url.Error, HTTP clients, InvalidInputError, errors.Is, and gRPC status codes.

Also explained in

Compare how 4 books explain errors.As →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.