Inspectopedia Help

Type assertion on errors fails on wrapped errors

Reports type assertion or type switch on errors, e.g., err.(*MyErr) or switch err.(type), and suggests using errors.As instead.

Since Go 1.13, errors can be wrapped using the fmt.Errorf function with the %w verb. Therefore, type assertion or type switch on errors may fail on wrapped errors. The preferred way for checking for specific type of error since Go 1.13 is to use the errors.As function from the standard library.

The quick-fix replaces type assertion and type switch on errors with a call to errors.As.

Example

errFoo, ok := err.(*ErrFoo) switch err.(type) { case *ErrBar: }

After the quick fix is applied:

var errFoo *ErrFoo ok := errors.As(err, &errFoo) var errBar *ErrBar switch { case errors.As(err, &errBar): }

Inspection Details

Available in:

GoLand 2023.3

Plugin:

Go, 233.SNAPSHOT

Last modified: 13 July 2023