Essential Go Error handling  Edit on GitHub      File Issue

Good practices for error messages

Good error messages help in debugging problems.

In production deployments error messages are logged. When something goes wrong log file is the main source for debugging clues.

When creating error messages, think about that and include as much useful information as possible.

Bad error message:

func openLog(path string) (io.Reader, error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, errors.New("failed to open log file")
    }
    ...
}

Better error message:

func openLog(path string) (io.Reader, error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, errors.New("openLog('%s'), os.Open() failed with '%s'", path, err)
    }
    ...
}

Second version of error message includes more debugging clues:

  ↑ ↓ to navigate     ↵ to select     Esc to close