Wrap & Unwrap errors in Go
- tags: Go
- source: “Wrap and Unwrap Errors in Go (Golang) | Gosamples.Dev.” Accessed October 12, 2022. https://gosamples.dev/wrap-unwrap-errors/.
Overview⌗
Since Go1.13, there is a new feature about error add to go: Wrap & Unwrap errors. Let’s start from a simple example:
Its output:
Let’s add more line to see how about to continual unwrap it:
Its output:
As we can see above, here is the conclusions:
- The
errors.Is
could always check which the error is; - The
errors.Unwrap
returns error the first wrapped error directly, which means we can’t get the errors amid the chain; - Calling
errors.Unwrap
on a non-wrapped error or nil pointer, the nil pointer will always be returned.
Does it Help for Error Tracing Purpose?⌗
As I already known, some logging frameworks/utilities provide like https://github.com/uber-go/zap provide a mechanic to print the invocation stacktrace of error. I’m wonder if this help.
Let’s see a example:
Its output:
Ooops, the zap output output stacktrace based where its call, not the error.
We can do it with a Stack field that provided zap.
Conclusion: it does help for error tracing purpose, but only with the provided context that surround by “[…]”.