Go Reference ยท Errors, I/O and Files
Go errors.As() function
Reference for Go errors.As and errors.AsType: find an error of a given type in a wrapped chain, read its fields, pointer targets, interfaces and the panic rule.
errors.As(err, &target) looks through the chain of err for the first error whose type can be assigned to the variable target points to. If it finds one, it stores it in target and returns true. That is how you get at the fields or methods of a specific error type after the error has been wrapped on its way up.
Where errors.Is compares values, errors.As matches types. The second argument must be a pointer to the variable that will receive the match, which is why you write &target.
var pe *fs.PathError if errors.As(err, &pe) { fmt.Println(pe.Path) }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func As(err error, target any) bool
| Name | Description |
|---|---|
err |
The error whose chain is searched. May be nil (the result is false). |
target |
A non-nil pointer to a variable of an interface type or of a type that implements error. The first matching error is stored there. |
Returns: true if a match was found and assigned.
Panics: if target is nil, not a pointer, or points to a type that is neither an interface nor an error implementation. go vet reports this at build time.
Usage notes
- Pointer to what you want. If your error type is used as
*MyErr, declarevar me *MyErrand pass&me. If errors are plain values (MyErr{}), declarevar me MyErr. A mismatch between the two silently returns false. - First match wins. The chain is searched from the outside in, and also through errors built by
errors.Joinor multiple%wverbs. - An
As(any) boolmethod on an error lets it supply a different type for the match; it is rarely needed. - Prefer
Isfor sentinels. UseAsonly when you need the data inside the error or want to match an interface. - Interface targets are good for behavior checks, such as
Timeout() boolon network errors. - Typed alternative: since Go 1.26 the generic
errors.AsType[T](err)returns the match and a bool without a pre-declared variable, for examplepe, ok := errors.AsType[*fs.PathError](err). It is checked at compile time, so it cannot panic likeAs.errors.Asworks in every version since 1.13. - Wrapped errors are not copies: the stored value is the very error in the chain, so a pointer target lets you modify it.