Inspectopedia 2024.3 Help

Type assertion on errors fails on wrapped errors

Reports type assertion or type switch on errors, for example, 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 fails on wrapped errors. The preferred way for checking for a specific error type is to use the errors.As function from the standard library as this function traverses the chain of the wrapped errors while checking for a specific error type.

For more information about errors.As, refer to working with Errors in Go 1.13.

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): }

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

GoTypeAssertionOnErrors
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Go | Probable bugs

Inspection Details

By default bundled with:

GoLand 2024.3, Qodana for Go 2024.3,

Can be installed with plugin:

Go, 243.23131

Last modified: 03 December 2024