Skip to content

go.error_type_assertion

Correctness Medium

Detects error type assertions using direct type assertion instead of errors.As().

Direct type assertions on errors:

  • Miss wrapped errors — Wrapped errors don’t match direct type checks
  • Break error chains — Go 1.13+ error wrapping is ignored
  • Lose error context — Miss errors wrapped with fmt.Errorf("%w")
// ❌ Before (misses wrapped errors)
if e, ok := err.(*MyError); ok {
handleMyError(e)
}
// ✅ After (handles wrapped errors)
var myErr *MyError
if errors.As(err, &myErr) {
handleMyError(myErr)
}
  • err.(*Type) type assertions
  • switch err.(type) without unwrapping
  • Missing errors.As() for custom error types

Unfault replaces type assertions with errors.As():

var e *MyError
if errors.As(err, &e) {
// ...
}