Handling an error

suggest change

In Go, errors can be returned from a function call. The convention is that if a function can fail, the last returned argument is an error.

func DoAndReturnSomething() (string, error) {
    if os.Getenv("ERROR") == "1" {
        return "", errors.New("The function failed")
    }

    // The function succeeded.
    return "Success!", nil
}

You use multiple variable assignments to check if the function failed.

result, err := DoAndReturnSomething()
if err != nil {
    panic(err)
}

// This is executed only if the function didn't return an error
fmt.Println(result)

If you are not interested in the error, you can simply ignore it by assigning it to _.

result, _ := DoAndReturnSomething()
fmt.Println(result)

Of course, ignoring an error can have serious implications. Therefore, this is generally not recommended.

If you have multiple method calls, and one or more methods in the chain may return an error, you should propagate the error to the first level that can handle it.

func Foo() error {
    return errors.New("I failed!")
}

func Bar() (string, error) {
    err := Foo()
    if err != nil {
        return "", err
    }

    return "I succeeded", nil
}

func Baz() (string, string, error) {
    res, err := Bar()
    if err != nil {
        return "", "", err
    }

    return "Foo", "Bar", nil
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents