Error Handling in Go: Errors Package
Introduction
Error handling is a critical aspect of programming, especially in a language like Go, which emphasizes simplicity and reliability. The "errors" package in Go provides the basic functionality for creating and handling errors.
Creating Errors
To create an error in Go, you can use the errors.New
function provided by the "errors" package. This function returns an error with the specified message.
import "errors"
err := errors.New("an error occurred")
Returning Errors
Functions in Go often return an error as the last return value. This allows the caller to check if an error occurred and handle it appropriately.
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
Handling Errors
When calling a function that returns an error, you should always check the error and handle it if necessary.
result, err := divide(4, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
Creating Custom Errors
You can create custom error types by implementing the error
interface, which requires a Error()
method.
type MyError struct {
msg string
}
func (e *MyError) Error() string {
return e.msg
}
func doSomething() error {
return &MyError{"something went wrong"}
}
Wrapping Errors
The "errors" package also provides the errors.Wrap
function, which allows you to add context to an existing error.
import "github.com/pkg/errors"
func readFile(filename string) ([]byte, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, errors.Wrap(err, "failed to read file")
}
return data, nil
}
Unwrapping Errors
Go 1.13 introduced the errors.Unwrap
function, which allows you to retrieve the underlying error.
wrappedErr := errors.Wrap(err, "additional context")
originalErr := errors.Unwrap(wrappedErr)
Conclusion
Error handling in Go is straightforward but powerful. By using the "errors" package, you can create, return, handle, and add context to errors effectively.