On Friday, 31 December 2021 at 08:10:49 UTC Henry wrote:

> The purpose of error wrapping is to give contextual information about the 
> error. It is supposed to help you understand and locate the error. For 
> instance, *"invalid filename"* is not particularly useful when compared 
> to *"fail to load customer data: invalid filename"*. Error wrapping is a 
> stack trace in a human-friendly language.


I disagree with that explanation, because what you describe can be done 
without wrapping:
return fmt.Errorf("Failed to load customer data: %v", err)
or with wrapping:
return fmt.Errorf("Failed to load customer data: %w", err)

Both provide exactly the same human-friendly trace.  The difference is that 
with the wrapped error, the error value can be destructured to retrieve the 
"cause" error object, and hence to match on that object. It's an invitation 
to your API consumer to couple directly to error types which your code 
doesn't return, but which originate from elsewhere, typically system 
libraries or third-party libraries.

The question then is, under what circumstances is that a good idea?  It 
depends.  Perhaps one example is if your code is using an underlying 
database API, and you are happy to expose raw database-level errors.  That 
allows your own library to wash its hands of responsibility of how to deal 
with these, and let the consumer deal with them if it wants to.  (Was it a 
temporary connection error? Was it a uniqueness constraint violation?  Not 
My Problemâ„¢)

-- 
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 on the web visit 
https://groups.google.com/d/msgid/golang-nuts/fa907dec-1dc7-4909-9743-4d91eb146481n%40googlegroups.com.

Reply via email to