Shorter wrapped error handling in Go

· 136 words · 1 minute read

With Go 1.13 error wrapping was standardised with an interface in the standard library. When properly handling errors, you end up dealing with it a lot. The blog post suggests the following:

var e *QueryError
if errors.As(err, &e) {
	// err is a *QueryError, and e is set to the error's value
}

On the other hand, the Go convention for error variables in conditional blocks is:

if err := os.Unlink(..); err != nil {
	// handle error
}

I think it can be very nice to have the errors on one line and the variable scoped to the conditional blocks. However, this does not work:

if e := &QueryError{}; errors.As(err, &e) {
	// handle error
}

You need to help the compiler a bit:

if e := (&QueryError{}); errors.As(err, &e) {
	// handle error
}