Pkg/errors - error type assertion vs error.Cause()

Yesterday I just realized how “dangerous” the pkg/errors lib could be if used without proper attention.
I was trying to check if an error returned by one of my functions was a net.Error generated by a timeout.
I thought to use an error type assertion like this:

// myFunction returns an error
err := myFunction()
netErr, ok := err.(net.Error)
if ok && netErr.Timeout() {
	doSomething()
}

Seems legit but once you adopt pkg/errors in your codebase, it is not going to work anymore.
I wasn’t thinking that inside myFunction() execution the error was wrapped to add context, changing the nature of the error type.
Luckily I found out the problem and change the type assertion with the proper code:

// myFunction returns an error
err := myFunction()
switch err := errors.Cause(err).(type) {
case net.Error:
	if err.Timeout() {
		doSomething()
	}
}

And now my question:
Is there any way to add a custom lint check for error type asserts in a project that adopt pkg/errors lib?
I would like to avoid this error again.
Thanks

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.