11

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...)

3 Answers 3

24

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.

Sign up to request clarification or add additional context in comments.

10 Comments

thx, that's really thoroughly explained! though about "having a new custom error type for every function or use-case is unsustainable, and makes your code unreadable and impossible to reason about"... dunno, that's kind of what I end up doing when writing code in languages that use exceptions... though I wouldn't say the resulting code is anywhere close to "easy to reason about", I agree ...so ok, I'll try the "Go way" as "when in Rome"... :)
@NeuronQ: Exceptions are an anti-pattern in a modern language like Go. They're solving a problem that no longer exists in modern programming languages which allow multiple return values, so using obsolete patterns like that in a modern language will cause you pain :)
@NeuronQ: Exceptions were created as a way to pass out-of-band error information in languages that only allowed a single return value (like C). In such languages, it's pretty much the only option for error handling. In a language like Go, where multiple return values are possible, there's no reason to use exceptions for standard errors, so I'd say that makes it an anti-pattern.
@NeuronQ Yes, several languages (Python, Perl, etc) allow multiple return values also use exceptions. That's one of the ugliest features of these languages, IMO.
last note though: in theory I like the pattern of "exceptions for technical/implementation/infrastructure errors, and error return values for business logic errors that usually need detailed responses given to the user/client" which could work great in languages like Python and JS... and that I've used in my code before... but I've never managed to convince anyone else to adhere to it, dunno why :( (so team-wise I consider it a failure, and I abandoned using it)
|
2

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 {

7 Comments

thx! pointer it is then, as using error forces me to add an ugly err := err.(DetailedError) type assertion so I can access extra fields like err.x...
@NeuronQ The idiomatic way is to have error as the return type instead of the custom error type (DetailedError). And at the point where you're interested in the details of the error you do type assertion, which is also idiomatic Go, whether it's ugly or not is subjective.
IMO, returning a non-error as an error is infinitely more ugly than a type assertion.
@NeuronQ I've added an explanation to my answer above. Let me know if you need further explanation.
Another reason not to return *DetailedError is that some caller might be tempted to treat it as a generic error and return it to their caller. But a nil *DetailedError is not a nil error, since it includes a known type, so the caller's caller will think there was an error, even if there wasn't. And then when they try to log the message, they'll get a panic because the value is still nil. See play.golang.org/p/m4S7GDfb2Y You should just use the error type and have the smart caller check and cast it. Typed errors are just not idiomatic in go.
|
0

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}
}

5 Comments

No, this is not idiomatic at all. The idiomatic approach is to return an error, which is already an interface.
So you prefer to cast the custom error, rather that safely return it as an output? Is there any reason to back this decision?
Again, there is no casting in Go.
Aside from that, you should always, always return an error. If you need access to custom aspects of that error, yes, you should do a type assertion.
Why do we have an output signature, if we can assert any type we want? This doesn't make sense. Also, is there any logical reason to "always, always" return an error?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.