In Go, error handling is implemented using the built-in error type. The error type is an interface defined as:
gotype error interface { Error() string }
Any type that implements the Error() string method can be used as an error type. Go encourages explicit error handling rather than using exception mechanisms. This means that functions should explicitly return error as one of their return values when they may return an error.
Basic Steps for Error Handling
- Check for Errors: After calling a function that may return an error, you should immediately check if the error is
nil. - Handle Errors: If the
erroris notnil, you should handle it appropriately, such as logging the error, returning the error, or conditionally handling based on the error type. - Propagate Errors: Sometimes, the current function cannot handle the error, so it can choose to return the error to its caller, allowing the caller to decide how to handle it.
Example Code
The following is a simple example illustrating how to check and handle errors in Go:
gopackage main import ( "errors" "fmt" ) func canFail(a int) (int, error) { if a < 0 { return 0, errors.New("input must be non-negative") } return a * 2, nil } func main() { result, err := canFail(-1) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", result) } }
In the above example, the function canFail may return an error. We check for the error immediately after calling the function and decide on subsequent actions based on whether the error is present.
Best Practices
- Fail early to avoid deeply nested code: After handling an error, return as early as possible to avoid deeply nested code.
- Custom error handling: Create more descriptive error types by implementing the
errorinterface. - Use
errors.Isanderrors.As: Starting with Go 1.13, these functions can be used to check the type or value of an error.
Advanced Error Handling
For more complex error handling, Go provides mechanisms like panic and recover to handle critical situations in the program, but this usage should be used with caution, typically only in scenarios where recovery is impossible.
By using this explicit error handling approach, Go ensures transparency and predictability in error handling, which helps in building stable and maintainable systems.