![]() |
VOOZH | about |
In Go, error handling is done by returning error values instead of using try-catch like in Java or Python. This approach ensures explicit error handling, improving code clarity and control.
The error type in Go is an interface with a single method:
type error interface {
Error() string
}
Any type implementing this method is treated as an error, keeping error handling simple and avoiding complex exception hierarchies.
errors.NewGo provides a simple errors package for creating basic error messages. Here's how you can create and return an error using errors.New:
Error: number is negative
Explanation:
checkNumber function returns an error if the number is negative.nil error.nil for No ErrorWhen no error occurs, it's common to return nil as the error value. This is the default "zero" value for errors in Go:
return "operation successful", nilFor more complex error handling, Go provides fmt.Errorf to wrap errors with additional context. This feature is incredibly useful for tracing the source of errors and understanding their context as they bubble up through function calls.
Example:
Error: number is negative
The %w verb in fmt.Errorf can wrap an error to preserve its context for further investigation:
err := fmt.Errorf("failed operation: %w", errors.New("network timeout"))
originalErr := errors.Unwrap(err)
fmt.Println(originalErr) // Output: network timeout
In Go 1.13 and later, the errors package provides the Unwrap function to extract the original error from a wrapped error. This is particularly useful when multiple layers of errors are involved.
err := fmt.Errorf("failed operation: %w", errors.New("network timeout"))
originalErr := errors.Unwrap(err)
fmt.Println(originalErr) // Output: network timeout
errors.IsGo provides the errors.Is function to compare errors, including errors that have been wrapped. This allows you to check if an error matches a specific predefined error, even if it has been wrapped multiple times.
Example:
Explanation:
ErrInvalidInput.errors.Is checks whether the error returned from validateInput matches the sentinel error, even if it's wrapped in additional context.While Go’s built-in error handling works for many scenarios, sometimes you need more specific error types. Custom error types can carry additional data and provide more context about the error.
Example:
Explanation:
CustomError struct with additional fields for Code and Message.Error method implements the error interface, allowing it to be used as an error.%w to preserve the original error.Go’s error handling is simple and explicit, treating errors as values for better code predictability. You can create errors using errors.New, wrap them with fmt.Errorf, or define custom error types. By following best practices, you can write robust, maintainable, and bug-free code, ensuring smooth development and production performance.