Whats the correct Go way to do handle errors
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
}
}
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
)
In Go, always check for errors. For example,
package main
import "fmt"
func doStuff() error {
err := SendMessageAndWait(db, "this is a test")
if err != nil {
return err
}
err = DoSomething(db, "this is a test")
if err != nil {
return err
}
err = CheckSomething(db, "this is another test")
if err != nil {
return err
}
err = SendMessageAndWait(db, "this is a third test")
if err != nil {
return err
}
return nil
}
func main() {
err := doStuff()
if err != nil {
fmt.Println("Error sending message", err)
}
}