How do I handle a lot of errors in Go?
I look at my code and find that it is full of error handlers:
err = result.Scan(&bot.BID, &bot.LANGUAGE, &bot.SOURCE)
if err != nil {
log.Fatalf("result.Scan: %v", err)
return
}
fileName, err := copySourceToTemporaryFile(bot)
if err != nil {
log.Fatalf("copySourceToTemporaryFile: %v", err)
return
}
...
And a lot of lines look like:
// do something
// handle error
// handle error
// handle error
// do something 2
// handle error
// handle error
// handle error
Can I create a default handler that prints an error and stops processing, or at least move out this "error-handler-garbage" out of my code logic?
That reminds me of the recent Errors are values by Rob Pike, as well as Mr. Rob Pike taught me about practice of error handling in Go at GoCon 2014
One technique was to define an object called an
errWriter
:If the
error
is "real", you should (have to) handle it if you don't want unexpected panics at runtime.To supplement VonC's answer about the
errWriter
technique, there are more cases where you can reduce error handling code:These are the cases when you know that even though a function or method may return an
error
, it will not (e.g. you're supplying the parameters from source code which you know will work). In these cases you (or the author of the library) can provide helper functions (or methods) which do not return theerror
but raise a runtime panic if it still occurs.Great examples of these are the
template
andregexp
packages: if you provide a valid template or regexp at compile time, you can be sure they can always be parsed without errors at runtime. For this reason thetemplate
package provides theMust(t *Template, err error) *Template
function and theregexp
package provides theMustCompile(str string) *Regexp
function: they don't returnerror
s because their intended use is where the input is guaranteed to be valid.Examples: