Go 1.27 reference · Errors, Context and Time
Go errors.Is and errors.As Function
Check whether an error chain contains a specific error value (Is) or an error of a specific type (As).
Go 1.27
Syntax
func Is(err, target error) bool func As(err error, target any) bool
Parameters
| Parameter | Description |
|---|---|
Is(err, ErrX) |
Sentinel error comparison through wrapping. |
As(err, &target) |
Extract a typed error from the chain. |
errors.Join |
Combine several errors. |
Examples
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func main() {
err := fmt.Errorf("get user 7: %w", ErrNotFound)
fmt.Println(err == ErrNotFound, errors.Is(err, ErrNotFound))
}
Output
false true
Run this on your computer — see “Get Started” for setup.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func main() {
_, err := os.Open("missing.txt")
var pathErr *fs.PathError
if errors.As(err, &pathErr) {
fmt.Println("op:", pathErr.Op, "path:", pathErr.Path)
}
joined := errors.Join(errors.New("a failed"), errors.New("b failed"))
fmt.Println(joined)
}
Output
op: open path: missing.txt a failed b failed
Run this on your computer — see “Get Started” for setup.
Related
fmt.Errorf· Create an error with a formatted message; the %w verb wraps another error so errors.Is and errors.As can find it.- Go Error Handling · tutorial