error handling & testing #11
-
I was looking to see how you dealt with error handling, and more specifically, how you test that the correct errors are being returned. I see that you check the error code, which could be common to a number of errors in a given function that you're testing, and then you check the end-user error message itself, which is specific to this particular error instance.
This seems to make sense, however, I'm curious why you opted for this over creating sentinel errors in your domain package:
And then your tests would check against that and wouldn't need to change as your end-user messages change. If the project were bigger, would you consider doing it differently or this still the approach you'd choose? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hi Daniel, great question. I used to use sentinel errors quite a bit but I've changed my approach to use code/message for a couple of reasons:
|
Beta Was this translation helpful? Give feedback.
-
Hi Ben, Thank you for sharing insights on how to structure Go projects! A few years ago I was researching this topic and I tried to incorporate your ideas as I understood them:
|
Beta Was this translation helpful? Give feedback.
Hi Daniel, great question. I used to use sentinel errors quite a bit but I've changed my approach to use code/message for a couple of reasons:
It works well with error wrapping—e.g.
fmt.Errorf("foo: %w, err)
. Ultimately I want to test what the end-user will see and not the wrapped error message (which I'll write to the log).It works well over a network boundary. If you use parse an incoming error message from another server using
errors.New(s)
then that error won't==
the sentinel error even though they have the same text.Codes translate well to implementation-specific error codes (e.g.
http
orgrpc
).