In Golang, there are multiple idiomatic approaches for handling errors.
Authors often declare fixed error variables following the naming convention Err.... For example:
var ( ErrSomethingBad = errors.New("some string") ErrKindFoo = errors.New("foo happened") )
Declaring error types (...Error) with specific information useful to callers is another common practice.
type SomeError struct { // extra information, whatever might be useful to callers // (or for making a nice message in `Error()`) ExtraInfo int } type OtherError string func (e SomeError) Error() string { /* … */ } func (e OtherError) Error() string { return fmt.Sprintf("failure doing something with %q", string(e)) }
Ad Hoc Errors
If you don't expect users to need to test for specific errors, you can create ad hoc errors using errors.New.
func SomepackageFunction() error { return errors.New("not implemented") }
Using Standard Package Errors
You can utilize errors defined in standard packages like io.EOF. However, it's generally better to create custom errors for your own package.
func SomeFunc() error { return io.EOF }
Error Interfaces
Creating an error interface allows you to check specific behaviors or types.
type Error interface { error Timeout() bool // Is the error a timeout? Temporary() bool // Is the error temporary? }
Contextual Errors
Use this technique with Go 1.13 or later to provide additional context to an existing error.
func SomepackageFunction() error { err := somethingThatCanFail() if err != nil { return fmt.Errorf("some context: %w", err) } }
The choice of approach depends on whether you anticipate users needing to test for specific errors and the potential for multiple users to implement their own error handling.
The above is the detailed content of How to Best Handle Errors in Go?. For more information, please follow other related articles on the PHP Chinese website!