3 ms·
It's generally good practice to not just `return err`, but to `return fmt.Errorf("some context: %w", err)`. That's usually enough for you to get what you need,
by jonathrg 3y ago
It's generally good practice to not just `return err`, but to `return fmt.Errorf("some context: %w", err)`. That's usually enough for you to get what you need, with a much higher signal-to-noise ratio than a stack trace.
- hamandcheese 3y agoCorrect me if I'm wrong but that still won't have file names and line numbers, right? So not only do you have to remember to wrap correctly, you need to take care to keep "some context: " a decently greppable string. I agree that wrapping errors that way is better than not, but I still find it a bit lacking.
- hiq 3y agoA (sad?) workaround I've seen is to intentionally misspell words in error / log messages so that they're unique enough. I guess I don't blame people doing that, but it does point to limitations of the language.
- pg_1234 3y agoThis, and sooo many other shortcomings, begins to explain why a submission extolling Go's error handling is already flagged. Go, and it's error handling (and for that matter it ludicrously verbose failure to bubble up errors) is a steaming pile of shit.
- threatofrain 3y agoI've started to add types to log messages so they can be easily sorted with a nice GUI. Your way works too.
- jonathrg 3y agoThat's correct. The resulting error message won't be a stack trace, but I find it spells out the problem quite nicely in practice. I haven't had issues with grepping for the errors, but I can see that it would be a problem in larger codebases.
- tetraodonpuffer 3y agoEasy way around this, when you create the error message always put in there the local epoch time of when you are writing it (copy from date, plug-in in your editor, whatever) making grepping for it trivial later on.
- za3faran 3y agoThat still does not let you know how you ended up at the error site. There could be multiple paths, and this approach does not help you determine that. Stack traces are still more useful.