Error handling is a fundamental aspect of development, whether it is ensuring that the applications can gracefully deal with unexpected outcomes or logging the detailed messages about the errors.
Like most programming, Go comes packed with tons of features of dealing and handling the errors from simple apps to massive code bases.
One of the most underrated but essential feature in error handling is error wrapping. Error wrapping is a technique that involves adding a context information to the returned error. It is basically like wrapping an error within an error.
Error wrapping plays a vital role in providing powerful and useful debugging messages as it provides for more precise and quick ways of identifying the source of the problem.
In this tutorial, we will explore about error wrapping and unwrapping in Go using the provided methods and packages.
Error Wrap Using the Fmt.Errorf Function in Golang
The most basic method of error wrapping is using the “fmt” package and the “Errorf” function. This allows us to create the formatted error messages with additional context as shown in the following example:
import (
"fmt"
"errors"
)
func main() {
flux := errors.New("error 43: Quantum Flux Capacitor Overload")
err := fmt.Errorf("fictional error: %w", flux)
fmt.Println(err.Error())
}
The previous code demonstrates how to use the “errors” package to wrap an error and add a context information.
Unwrapping the Error
To unwrap the error and retrieve the original error (in this case is the flux error), we can use the “errors.Unwrap” function from the “errors” package.
import (
"fmt"
"errors"
)
func main() {
flux := errors.New("error 43: Quantum Flux Capacitor Overload")
err := fmt.Errorf("fictional error: %w", flux)
originalError := errors.Unwrap(err)
if originalError != nil {
fmt.Println("Original Error:", originalError.Error())
} else {
fmt.Println("No original error found.")
}
}
This should unwrap the error and return the original error message.
Conclusion
In this post, we covered the fundamentals of working with the “error” package to wrap and unwrap the error messages.