Writing good error messages

suggest change

Good error messages help with debugging.

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

When creating error messages, keep that in mind 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, fmt.Errorf("openLog('%s'), os.Open() failed with '%s'", path, err)
    }
    ...
}

errors.New takes only a string, so the second version uses fmt.Errorf. It includes more debugging clues:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents