Home > Backend Development > Golang > How to Best Handle Errors in Go?

How to Best Handle Errors in Go?

Mary-Kate Olsen
Release: 2024-12-27 10:06:10
Original
542 people have browsed it

How to Best Handle Errors in Go?

Standard Error Variables in Go

In Golang, there are multiple idiomatic approaches for handling errors.

Custom Error Variables

Authors often declare fixed error variables following the naming convention Err.... For example:

var (
        ErrSomethingBad = errors.New("some string")
        ErrKindFoo      = errors.New("foo happened")
)
Copy after login

Error Types

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))
}
Copy after login

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")
}
Copy after login

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
}
Copy after login

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?
}
Copy after login

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)
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template