errors custom As

145 views
Skip to first unread message

Gert

unread,
Oct 24, 2019, 4:26:25 AM10/24/19
to golang-nuts
Hi, I fail to understand how the custom As is suppose to work?


Jake Montgomery

unread,
Oct 24, 2019, 12:53:32 PM10/24/19
to golang-nuts
I have not done much with the new errors stuff, but I'll try to help.

I assume you have read https://github.com/golang/go/wiki/ErrorValueFAQ  and https://blog.golang.org/go1.13-errors. There may be other posts as well.

These new error functions, Is() and As() are about error types. It looks like you are trying to transform an error of type PathErr into another error of type PathErr with a different value. That's not how it works.

I think most of the time As() will work because the error wraps another error of a different type. In that case the error should implement Unwrap() not As(). If your error encapsulates multiple error types, then you would need to implement As(). At least that is my understanding. For example, taking your code, and modifying it, so that PathErr can also be treated as an OtherErr could look like https://play.golang.org/p/qa4VU0PEP3v. But again, since there is only one type encompassed in PathErr, I think this might be more easily done with Unwrap like this: https://play.golang.org/p/v4gDgtlNxcQ

Good luck.

Gert

unread,
Oct 24, 2019, 3:34:55 PM10/24/19
to golang-nuts
Thx, examples helped allot in understanding

anderson...@blacklane.com

unread,
Oct 28, 2019, 6:31:32 AM10/28/19
to golang-nuts
The idea of As is to find an error in the wrapped errors, the error chain, which can be cast to the type you pass.

I played a bit with them and made some examples: https://github.com/AndersonQ/go1_13_errors/blob/master/main.go#L103
Have a look in the implementation of As, it's nice and simple to understand :) you migh eve try to debug to see it in action.
Reply all
Reply to author
Forward
0 new messages