Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 992
NeuronQ Avatar asked Sep 03 '17 10:09

NeuronQ


People also ask

How do you write an error in Golang?

You can create wrapped errors by using the %w flag with the fmt. Errorf function as shown in the following example. As you can see the application prints both the new error created using fmt. Errorf as well as the old error message that was passed to the %w flag.

What is if err != Nil?

if err != nil { return err } > is outweighed by the value of deliberately handling each failure condition at the point at which they occur. Key to this is the cultural value of handling each and every error explicitly.

How do you wrap an error in Go?

It does not matter that the error is wrapped. A simple comparison if err == ErrorInternal would give false in this case, so it is generally a better idea to use the errors.Is() function to compare errors equality. Then, we unwrap the error using the errors. Unwrap() and print it to the standard output.


2 Answers

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.

like image 190
Flimzy Avatar answered Oct 11 '22 00:10

Flimzy


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 {
like image 35
Uvelichitel Avatar answered Oct 11 '22 01:10

Uvelichitel