Handle Golang Errors with Stacktrace

Frank Chung
DeepQ Research Engineering Blog
1 min readAug 26, 2019

Error handling in Golang is simple and straight-forward, but its simplicity makes the error tracking a little bit difficult. E.g., Go programmers often decorate some debug message into a thrown error:

In this case, it is better to understand the error’s stacktrace for debugging. Golang runtime package provides a way to get the stack frames:

To implement a Golang error with stacktrace, we can define a traceable interface:

And implement the traceable interface with a customized error:

Finally we wrap the traceable error with some convenient utils like:

A traceable error is completed! Then we just replace fmt.Errorf by errors.Errorf, and call errors.StackTrace(err) to get the stacktrace of an error.

For detailed implementation, visit my github:

--

--