If we have the following method in GO:
GetCustomer(id string) (*Customer, error)
A customer for a given id may not exist in DB. When a customer is not found, the code can
return nil, nil
Is this considered bad coding practice in Go? Or would the idiomatic Go code would look like
return nil, errCustomerNotFound
The problem I see with the second approach is that you end up checking for this specific error and handling it seperately.
Are there examples in Go source or libraries where this situation arises and one of the approaches is preferred?
Update
If return nil, nil
is considered as not idiomatic. I was wondering why that is true in this case? As *Customer is a pointer, I want to return nil to indicate absence of value
GetCustomer(id string) (c *Customer, ok bool, err error)
and use the returnreturn nil, false, nil
. This is similar to getting a key from a map in which that key may or may not exist. – Ewersnil
in these sorts of cases I think it's no problem. Or if you're writing a public library then document that you returnnil
and keep it consistent if you have any otherGet*
functions. – Ewersreturn nil, nil
is not idiomatic Go. – Airwaynil
. – BetjemanThe problem I see with the second approach is that you end up checking for this specific error and handling it seperately.
use a standard error like sql.ErrNotFound (or similar). That the not found value is a customer, is a detail useful for logging, within your code, most of the time, there should be enough context to figure out that it was a customer. – Carrizales