> On Feb 4, 2025, at 4:59 PM, Darren Grant <darren.e.gr...@gmail.com> wrote:
> 
> What's the current best practice for getting a stack trace from an error 
> passed up from further down in the stack?
> 
> E.g. a web server middleware uses recover to catch panics. In the recover, we 
> want the stack trace of the code that created the first error in the stack.

Not sure if I would go so far as saying it is a "best practice," but you can 
create your own error type — call it TraceError? — and then you can call 
yourerrpkg.Wrap(err) whenever you want a TraceError and it will return `err` if 
`err` already contains a TraceError() or it will generate a TraceError() if 
not.  Or if you want to generate an error from scratch you can call 
NewTraceError().

Then when you handle the error — such as logging it — you can `errors.As()` to 
get the TraceError and access its String() or Stack() methods.

Here is a example demoing how it works:

https://go.dev/play/p/J9i1pxB0YFU <https://go.dev/play/p/J9i1pxB0YFU>

Any follow up questions, feel free to ask.

-Mike

P.S. I threw this together to answer the question, but if anyone else notices 
something I missed or did wrong, it would be great if you could mention it as I 
would actually like to use this code moving forward.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/153B81DA-6CD3-4139-A7DE-C482CFF838DD%40newclarity.net.

Reply via email to