liveBook · Manning

Errors.As

As explained in 100 Go Mistakes and How to Avoid Them

errors.As is a Go standard-library function that recursively examines an error chain for an error assignable to a specified target type.

errors.As recursively unwraps an error chain and reports whether any error matches a specified type. It is needed when %w wrapping hides the original type from a direct type switch. section 7.3 section 7.8

A wrapped transient error bypasses a type switch

After getTransactionAmount wraps a transientError with fmt.Errorf("failed to get transaction %s: %w", transactionID, err), switch err := err.(type) no longer matches transientError. Use errors.As instead: if errors.As(err, &transientError{}) { http.Error(w, err.Error(), http.StatusServiceUnavailable) } else { http.Error(w, err.Error(), http.StatusBadRequest) }. The target argument must be a pointer; otherwise the code compiles but panics at runtime. section 7.3

Use errors.As when callers must classify a specific error type regardless of whether it is returned directly or wrapped with additional context. section 7.3

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces wrapping, recursive unwrapping, type matching, and the runtime panic caused by a non-pointer target.
Examples
Demonstrates transientError, database failure propagation, and HTTP response handling.
What it assumes
Assumes familiarity with Go errors, type switches, and fmt.Errorf; teaches why %w wrapping changes direct type checks.
What you can do after
Diagnose/debug wrapped errors and route them according to their underlying type.
How it connects
Connects error wrapping, type switches, error types, fmt.Errorf, and errors.Is for value comparison.

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 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.