Go core
Browse topics

errors.As

Version
1.27
Since
1.13
Review
Draft

Summary#

Use errors.As to find the first error in an error tree that matches a concrete type or interface. The function writes the match through the target pointer.

Syntax#

go
var pathError *fs.PathError
if errors.As(err, &pathError) {
	fmt.Println(pathError.Path)
}

Example#

go
package main

import (
	"errors"
	"fmt"
	"io/fs"
)

func main() {
	cause := &fs.PathError{Op: "read", Path: "settings.json", Err: fs.ErrNotExist}
	err := fmt.Errorf("load configuration: %w", cause)

	var pathError *fs.PathError
	if errors.As(err, &pathError) {
		fmt.Println(pathError.Op, pathError.Path)
	}
}

Expected output#

Text
read settings.json

Common mistakes#

Pass &pathError when pathError is a *fs.PathError. The extra pointer level lets errors.As assign the target. A direct type assertion on the wrapper cannot see through it.

Version applicability#

errors.As was added in Go 1.13. Both the syntax and the example use io/fs, which requires Go 1.16 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0