4 ms·
I think you can just use the `Callers()` function from the "runtime" package to the get the call stack, though in general I think it's a bit overkill. I think w
by ThePhysicist 5y ago
I think you can just use the `Callers()` function from the "runtime" package to the get the call stack, though in general I think it's a bit overkill. I think what you should do instead is to wrap errors with '%w' [1], manually adding context to them as you pass them up your call stack. That leads to more readable code and won't incur any performance overhead. It's tempting to have the call stack available for debugging, but IMHO it creates too much overhead when doing it indiscriminately for all errors you generate, which for me also goes a bit against the "spirit" of Golang.
[1]: https://go.dev/blog/go1.13-errors https://go.dev/blog/go1.13-errors
- tsimionescu 5y agoHow many errors are you creating that you would start caring about overhead? And why do you think code is more readable if it's littered with guesses on what may be important to track down a problem, rather then the simple call stack?
- marhee 5y agoBecause the call stack does not include the value of function call arguments. A good error message does include the call arguments values relevant to the error AND those of the relevant variables. But I agree it takes upfront effort and often also need adjustments when debugging an issue later (i.e. adding more info to the error message and rerun).
- ThePhysicist 5y agoIn my typical Go code many errors are handled internally, e.g. "not found" type of errors returned by database methods. It would be pretty wasteful extracting full stack traces for these and in high-performance scenarios this can really hurt you. I think stack traces should be mostly reserved for interactive debugging and should not be included in user-facing errors. Why should the users of your program care that foo() called bar() called baz() which then produced an error? They want to know what went wrong and how to fix it (if it's "their" fault), and that is much easier if they get proper, context-specific errors (e.g. "CLI argument 'limit' must be between 1-10"). And if you need a stack trace for debugging a problem you should simply use panic().