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.

Wrapping and unwrapping errors

Wrapping and unwrapping errors

- Consider the all method being defined on the left. If an error occurs, a custom error implementation error table not found is initialized with the appropriate information. Before being returned, however, error is then wrapped with fmt.errorf to create a message that includes the type and method that caused the error. To wrap an error using fmt.errorf, we can use the percent W formatting verb meant for errors. On the right, shows a test for the all method. This test tries to assert that the error is of type error table not found. When an error is wrapped with the fmt.errorf method, the resulting type is that of a general error interface. As such, by wrapping the error table not found error with the fmt.errorf function, we have changed the results of the type of error. This also results in the test failing as the error is no longer an error table not found, but a different one. In order to get to the original error, we need to unwrap the errors until we reach the original one. This is…

Contents