Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the correct Go way to do handle errors

Tags:

go

This seems a bit stupid, surely theres a better way?

err = SendMessageAndWait(db, "this is a test")
if err != nil {
    fmt.Println("Error sending message", err)
    return
}
err = DoSomething(db, "this is a test")
if err != nil {
    fmt.Println("Error sending message", err)
    return
}
err = CheckSomething(db, "this is another test")
if err != nil {
    fmt.Println("Error sending message", err)
    return
}
err = SendMessageAndWait(db, "this is a third test")
if err != nil {
    fmt.Println("Error sending message", err)
    return
}
... x10 ...

Update: For the record, 5 years on from when I wrote this, I am now persuaded that this is a completely sufficient, and perhaps even better, way to handle errors clearly. Not saying its pretty though.

like image 369
Jay Avatar asked Jul 25 '14 05:07

Jay


2 Answers

Sadly that's the way it is in Go, however in a way you can make it cleaner:

func isError(err error, pre string) error {
    if err != nil {
        log.Printf("%v: %v", pre, err)
    }
    return err
}

func isErrorBool(err error, pre string) (b bool) {
    if err != nil {
        log.Printf("%v: %v", pre, err)
        b = true
    }
    return
}

func checkSomething() error {
    return nil
}

func main() {
    if err := isError(checkSomething(), "something failed"); err != nil {
        return /* err */
    }

    //if you don't want to return the error, just check it and die.
    if isErrorBool(checkSomething(), "something else failed") { 
        return
    }
}
like image 82
OneOfOne Avatar answered Sep 28 '22 10:09

OneOfOne


I would not just print an error and return nothing: the idea is to act on the error and return it (if no decisive action was taken, like a simple log).
Simply calling return is like ignoring the error completely as far as the rest of the application is concerned.

See "Best Practices for Errors in Go", which includes advices as:

Predefine errors

Given a small set of errors, the best way to handle this is to predefine each error publicly at the package level.

Provide information

custom error type is the best solution to this problem. Go's implicit interfaces make creating one easy

Provide stack traces

package errgo provides the functionality of wrapping an error into another one that records where the error happened.

(You have the same features in dropbox/godropbox/errors/errors.go)

like image 30
VonC Avatar answered Sep 28 '22 11:09

VonC