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()) }



