Closed richzw closed 3 years ago
I think the former is better.
Also consider testing for behavior:
err := testErrWrap(3)
var wrappedErr interface { Unwrap() error }
if errors.As(err, &wrappedErr) {
fmt.Println(errors.Unwrap(err))
}
But also of note, errors.Wrap(…)
double wraps your error: one WithMessage
and one WithStack
. So using errors.Unwrap(err)
on the error from errors.Wrap(ErrRPC, "call rpc err")
will not give you ErrRPC
.
@puellanivis , it seems the fmt.Println(errors.Cause(err))
could print the original error, and the output is error rpc
Yes, errors.Cause
will strip out all wrapping done with this package, and any other error wraps that implement interface{ Cause() error }
though since a lot of packages are switching to native errors with fmt.Errorf("%w", err)
wrapping, this won’t help you there.
We have one function that returns errors one of them is wrapped by
errors.Wrap()
, the others are not.We have two solutions, one is
the other is
We want to know the elegant way to distinguish errors are wrapped or not in Go?