rs / zerolog

Zero Allocation JSON Logger
MIT License
10.62k stars 572 forks source link

How to get the error type from a wrapped error #484

Closed conor-tread closed 1 year ago

conor-tread commented 2 years ago

So in order to have the stack trace in my error I need to call errors.Wrap and pass that back.

The problem Im having then, is when I handle the error I am currently type switching on the error type. But since its wrapped I can no longer do that, it doesnt work.

So how can I get at the type of the error that is in my wrapped error.

func myFunc() err {
   return &CustomError("This is a new custom error"), ""))
}

func main () {
    err := myFunc()
   switch err.(type) {
   case *CustomError: 
        //handle a custom error
   default: 
       // handle default
   }
}

I had a look at errors.As but im not a fan of the fact you have to instantiate a variable for an error before using it. From the above I would have to do something like:

func main () {
    err := myFunc()
   var customErr *CustomError 
   if errors.As(err, &customErr) {
        //handle a custom error
   } else {
       // handle default
   }
}

and then do another variable per possible error type.

mitar commented 1 year ago

Sorry, what has this issue with this package? Are you using Wrap just so that you can have a stack trace when logging? Si this the reason why you are asking the question here?

Anyway, using errors.As is the standard and idiomatic way in modern Go, so you should just go with it. You just instantiate a pointer to an error on stack, so it should be fine.