Errors As Non Pointer

ID

go.errors_as_non_pointer

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

reliability, suspicious

Description

Reports a call to errors.As(err, target) whose second argument is not a pointer. The target must be a non-nil pointer to either a type that implements error or to any interface type; errors.As sets it to the matched error in the chain. Passing a value instead of a pointer is a contract violation.

Rationale

errors.As panics at runtime when target is not a non-nil pointer to a type implementing error. The mistake is to write errors.As(err, target) instead of errors.As(err, &target). Because the panic happens only on the error path, it is rarely exercised by tests, so it can sit in production unnoticed. Detecting the non-pointer target makes the contract violation visible at build time.

errors.As(err, myErr)   // FLAW — second argument must be a pointer

errors.As(err, &myErr)  // OK — address of the target

Remediation

Take the address of the target: errors.As(err, &target).