The order service
had a validation step.

It returned an error
if the quantity was wrong,
and nothing if it was fine.

type QtyError struct{ Qty int }

func (e *QtyError) Error() string {
return fmt.Sprintf("bad quantity %d", e.Qty)
}

func validate(o Order) error {
var err *QtyError
if o.Qty <= 0 {
err = &QtyError{o.Qty}
}
return err
}

The caller did the usual thing:

if err := validate(o); err != nil {
reject(o, err)
}

Every order was rejected.

Including the good ones.

Then the log line
that printed the reason
crashed with a nil pointer dereference.

Here is the mechanism.

In Go,
an interface value has two parts.

A type.

And a value.

It equals nil
only when both are empty.

validate returns error,
which is an interface.

Inside, err was a *QtyError
that happened to be nil.

Returning it
put the type *QtyError
into the interface,
with a nil pointer as the value.

Type filled in.

Value empty.

So err != nil
was true.

An interface holding a nil pointer
is not a nil interface.

The Go FAQ has a whole entry on it,
titled
"Why is my nil error value not equal to nil?"

And Error() ran
on a nil *QtyError,
reached for e.Qty,
and panicked.

The fix is small.

Return the interface,
not the concrete pointer:

func validate(o Order) error {
if o.Qty <= 0 {
return &QtyError{o.Qty}
}
return nil
}

That nil
is the untyped kind,
and it reaches the caller
as a true nil.

The rule underneath:

never declare a variable
of your own error type
and return it as error.

Declare it as error,
or return nil by name.

The same trap waits
anywhere a nil pointer
is handed to an interface.

A nil *bytes.Buffer
passed as an io.Writer.

A nil *Config
stored in an any.

Each one
looks like nothing
and compares as something.

When a check says
something is there
and you can see nothing,
ask what type
it was wrapped in.

– Serguey Asael Shinder