Standard Error Handlers in Go
Go has several idiomatic approaches for error handling:
1. Fixed Error Variables
var (
ErrSomethingBad = errors.New("some string")
ErrKindFoo = errors.New("foo happened")
)
2. Error Types
type SomeError struct {
ExtraInfo int
}
func (e SomeError) Error() string { /* … */ }
3. Ad Hoc Errors
func SomepackageFunction() error {
return errors.New("not implemented")
}
4. Standard Library Errors
func SomeFunc() error {
return io.EOF
}
5. Error Interfaces
type Error interface {
error
Timeout() bool
Temporary() bool
}
6. Wrapping Errors (Go 1.13 )
func SomepackageFunction() error {
err := somethingThatCanFail()
if err != nil {
return fmt.Errorf("some context: %w", err)
}
}
Choosing the Right Approach
The preferred methods are:
- Fixed error variables or error types for errors users may want to test specifically.
- Ad hoc errors or standard library errors for minor errors that are unlikely to be tested.
- Error interfaces for errors with specific behavior or properties.
- Wrapped errors for adding context to existing errors (Go 1.13 ).
Advantages:
-
Fixed Error Variables: Easy to test and compare.
-
Error Types: Extensible with additional information for error handling.
-
Ad Hoc Errors: Concise for minor errors.
-
Error Interfaces: Enforce specific error behavior and facilitate polymorphism.
-
Wrapped Errors: Provide context without creating custom error types.
Further Reading:
- [Effective Go on Errors](https://go.dev/doc/articles/errors)
- [The Go Blog: Error handling and Go](https://blog.golang.org/error-handling-and-go)
- [Dave Cheney: Inspecting Errors](https://dave.cheney.net/2016/04/07/inspecting-errors)
- [Peter Bourgon: Programming with errors](https://go.dev/blog/errors)
The above is the detailed content of What are the Best Practices for Handling Errors in Go?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn