NeuronQ
NeuronQ

Reputation: 8195

Return nil or custom error in Go

When using a custom Error type in Go (with extra fields to capture some details), when trying to return nil as value of this type, I get compile errors like cannot convert nil to type DetailedError or like cannot use nil as type DetailedError in return argument, from code looking mostly like this:

type DetailedError struct {
    x, y int
}

func (e DetailedError) Error() string {
    return fmt.Sprintf("Error occured at (%s,%s)", e.x, e.y)
}

func foo(answer, x, y int) (int, DetailedError) {
    if answer == 42 {
        return 100, nil  //!! cannot use nil as type DetailedError in return argument
    }
    return 0, DetailedError{x: x, y: y}
}

(full snippet: https://play.golang.org/p/4i6bmAIbRg)

What would be the idiomatic way to solve this problem? (Or any way that works...)

I actually need the extra fields on errors because I have detailed error messages constructed by complex logic from simpler ones etc., and if I would just fall back to "string errors" I'd basically have to parse those strings to pieces and have logic happen based on them and so on, which seems really ugly (I mean, why serialize to strings info you know you're gonna need to deserialize later...)

Upvotes: 11

Views: 24338

Answers (3)

David Cruz
David Cruz

Reputation: 71

The idiomatic way to solve your problem is to return the error interface.

If you actually need a function that is not part of the error interface, you should create a new interface that extends the error interface.

type DetailedErrorInterface interface {
  error
  GetX() int //need to implement
  GetY() int //need to implement
}

Then, you must change your function to return this interface:

func foo(answer, x, y int) (int, DetailedErrorInterface) {
  if answer == 42 {
    return 100, nil
  }
  return 0, DetailedError{x: x, y: y}
}

Upvotes: 0

Jonathan Hall
Jonathan Hall

Reputation: 79586

Don't use DetailedError as a return type, always use error:

func foo(answer, x, y int) (int, error) {
    if answer == 42 {
        return 100, nil  //!! cannot use nil as type DetailedError in return argument
    }
    return 0, DetailedError{x: x, y: y}
}

The fact that your DetailedError type satisfies the error interface is sufficient to make this work. Then, in your caller, if you care about the extra fields, use a type assertion:

value, err := foo(...)
if err != nil {
    if detailedErr, ok := err.(DetailedError); ok {
        // Do something with the detailed error values
    } else {
        // It's some other error type, behave accordingly
    }
}

Reasons for not returning DetailedError:

It may not appear to matter right now, but in the future your code may expand to include additional error checks:

func foo(answer, x, y int) (int, error) {
    cache, err := fetchFromCache(answer, x, y)
    if err != nil {
        return 0, fmt.Errorf("Failed to read cache: %s", err)
    }
    // ... 
}

The additional error types won't be of DetailedError type, so you then must return error.

Further, your method may be used by other callers that don't know or care about the DetailedError type:

func fooWrapper(answer, x, y int) (int, error) {
    // Do something before calling foo
    result, err := foo(answer, x, y)
    if err != nil {
        return 0, err
    }
    // Do something after calling foo
    return result, nil
}

It's unreasonable to expect every caller of a function to understand a custom error type--this is precisely why interfaces, and in particular the error interface, exists in Go.

Take advantage of this, don't circumvent it.

Even if your code never changes, having a new custom error type for every function or use-case is unsustainable, and makes your code unreadable and impossible to reason about.

Upvotes: 24

Uvelichitel
Uvelichitel

Reputation: 8490

DetailedError struct zero value isn't nil but DetailedError{}. You can either return error interface instead of DetailedError

func foo(answer, x, y int) (int, error) {

or use pointer

func foo(answer, x, y int) (int, *DetailedError) {
...
//and
func (e *DetailedError) Error() string {

Upvotes: 2

Related Questions