Chapter 3 – Writing a Custom Error Type
In the first chapter, we learned the basics of errors in go. How to create an error with a particular message. Then we looked into exposing different types of errors in our packages so that consumers of our code can handle them differently, if appropriate.
In the second chapter of our series, we learned how to enhance our error messages to provide better user information. We learned how to add additional information to our error messages while retaining the ability to distinguish between different error cases. The additional information can be used by whoever receives the error message to hopefully resolve their issue. In our example of a configuration provider, we return a syntax error if the provided configuration is in an invalid syntax.
We then learned that we can wrap errors with additional information, such as the line number of the syntax error. This additional information is not easily machine-readable, and we cannot use it to refine our automated error handling, such as retry logic. We can only differentiate based on the error we wrapped with the additional information.
In this part, you will learn how to create your own error types, which can have any behavior you may find helpful. We will use this to resolve an issue we found in the last chapter: how to decorate an error that was returned from a library our application uses, decide how to handle it based on our sentinel errors, and yet, still have access to the original error. Once you know how to implement custom error types, we will show you some examples where this may be useful.
(more…)