Extract types with errors.As
Extract types with errors.As
Use errors.As to locate an error of a particular type in an error tree. Declare a variable of the desired error type, then pass its address as the target. On success As assigns the matching value and returns true; check that boolean before using the target.
package main
import ( "errors" "fmt")
type FieldError struct{ Field string }
func (e *FieldError) Error() string { return "invalid " + e.Field }func main() { err := fmt.Errorf("form: %w", &FieldError{Field: "email"}) var fe *FieldError if errors.As(err, &fe) { fmt.Println(fe.Field) }}FieldError implements error through its pointer method. fe has type *FieldError, so &fe has type **FieldError; As needs the address of the variable it will set. A direct type assertion on the outer wrapper would not extract this inner error.
Expected output:
emailHandle a nonmatching error
package main
import ( "errors" "fmt")
type LimitError struct{ Max int }
func (e LimitError) Error() string { return "limit exceeded" }func main() { var le LimitError fmt.Println(errors.As(errors.New("other"), &le)) err := fmt.Errorf("check: %w", LimitError{Max: 5}) if errors.As(err, &le) { fmt.Println(le.Max) }}This custom error uses a value receiver, so the target is a LimitError variable and its address. As can also match interface targets and custom As methods. Invalid targets panic. A matching typed-nil pointer may still be nil, so enforce non-nil error contracts or check before dereferencing.
Expected output:
false5Try it locally
Define *CodeError with Code int and Error() string. Wrap a non-nil CodeError with code 7. Extract it with errors.As and print Code on success.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 04: Extract types with errors.As
Check the lesson objective before moving on.
For var e *FieldError, what target should As receive?
What does As return when no matching type exists?