Writing good error messages
suggest changeGood 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:
- which function generated the error
- the path of the file we were trying to open
- the error from
os.Open, so we can tell whether the file does not exist, access was denied, and so on
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents