I am wrapping errors (to add context) and am afterwards distinguishing between two errors. This is a scenario that I am currently using for tests. (Did the function recognise the error correctly?) My question is how I can reduce the verbosity.
I have two functions that create different errors:
func a() error {
return errors.New("a")
}
func b() error {
return errors.New("b")
}
They are both called by a third function that propagates the erorr.
func doStuff() error {
err := a()
if err != nil {
return WrapA{err}
}
err = b()
if err != nil {
return WrapB{err}
}
return nil
}
In my main function, I distinguish between both errors.
func main() {
fmt.Println("Hello, playground")
err := doStuff()
switch err.(type) {
case WrapA:
fmt.Println("error from doing a")
case WrapB:
fmt.Println("error from doing b")
case nil:
fmt.Println("nil")
default:
fmt.Println("unknown")
}
}
So far, so good. Unfortunately, to implement WrapA and WrapB, I need a lot of code:
type WrapA struct {
wrappedError error
}
func (e WrapA) Error() string {
return e.wrappedError.Error()
}
func (e WrapA) Unwrap() error {
return e.wrappedError
}
type WrapB struct {
wrappedError error
}
func (e WrapB) Error() string {
return e.wrappedError.Error()
}
func (e WrapB) Unwrap() error {
return e.wrappedError
}
In other languages, I would create a single Wrap struct and let WrapA and WrapB inherit from Wrap. But I don't see a way to do this in Go.
Any ideas on how to reduce the clutter?
Go Playground https://play.golang.org/p/ApzHC_miNyV
EDIT:
After seeing jub0bs answer, I want to clarify:
Both a() and b() are callbacks I have no control over. They may return various errors. This is the reason why I wrap them.