Creating, Wrapping and Handling Errors
·
459 words
·
3 minutes read
In Go, although errors are a controversial subject, they are in fact very simple. As programmers of Go we also spend a lot of our time writing if err != nil
. But we often also need to create these errors and pass them back to other functions to handle.
The errors
package allows us to create errors, as per the error interface, which can be dealt with like any other error. In our example below, we handle the error within main()
and produce the error in DoSomething()
.
Basic Example:
|
|
Wrapping Errors
By using the pkg/errors package instead of the stdlib copy, we’re able to Wrap()
and Unwrap()
errors as they bubble up. This gives the great advantage of adding context along the way. If you see a generic and specific error in a large code base they can be difficult to track down without this added context.
|
|
Handling Errors
Using the Is()
function when checking errors is a more thorough way to check errors, as opposed to a line like err == exampleError
which would also work if the error didn’t use wrapping.
|
|