fix: sentinel errors should not have stack traces #2042
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
While debugging a program which is using badger I noticed that stack traces returned from my code (which uses errors with stack traces) are useless. I found the reason: badger uses sentinel errors (great!) but it creates them with stack traces at the "global init time" (e.g.,
var ErrFoo = errors.New(...)
) and not at "return from function time". Because of that I was seeing stack traces like:Instead of a stack trace which would show me where the call which is returning sentinel error is made.
Solution
Ideally, one would create all sentinel errors without stack traces (standard errors package works great for that) and then when the error happens in a function, you return
errors.WithStack(ErrFoobar)
instead of justErrFoobar
. This means that sentinel error is then annotated with a stack trace at the place where the error happens. But if you do that, then you have to check for sentinel errors witherrors.Is
instead of just comparing errors with equality (==
). That might be a breaking change for people who are not usingerrors.Is
as they should. Because badger's own codebase uses equality instead oferrors.Is
I decided to not do this in this PR, but instead:Just make sentinel errors without stack traces. This allows me to annotate with a stack trace inside my program (otherwise my program does not do so because if finds an existing stack trace and assumes it is a deeper one) and I get at least that part of the stack trace. Equality still works as usual.
I suggest this is merged this way and in v5 of badger
errors.WithStack
and requirederrors.Is
are introduced.Side note
Some time ago I made this errors package for Go which fixes various issues in
github.com/pkg/errors
and also has direct support for sentinel (in that package called "base") errors. It also has some features badger has in itsy
package for dealing with errors. You could consider adopting that package to have a comprehensive errors handling in badger.