From the course: Go for Developers: Practical Techniques for Effective Coding

Unlock this course with a free trial

Join today to access over 24,900 courses taught by industry experts.

Using errors.As() and errors.Is()

Using errors.As() and errors.Is()

- While unwrapping an error allows us to get to the original underlying error, it does not allow us to get access to any of the other errors that it might have been wrapped with. For example, on the left, the wrapper function takes an error and wraps it in three new errors. In the test, we want to assert that ErrorA was part of the stack of errors returned. However, the wrapped error is of type ErrorC, and not ErrorA, so the test fails. So how do we check if the wrapped error has ErrorB in its stack, and how do we get access to the ErrorA error? The errors package provides two functions, Errors.Is and Errors.As, that will help us with these questions. When working with errors, we often don't care about the underlying error. There are times, however, when we do care about that underlying error and want to get access to it. The errors.As function is designed to do this. It takes an error and a type to match against. If the error matches the type, it will return the underlying error. If…

Contents