Question to all you Gophers out there: How do you deal with custom errors that include more information and different kinds of matching them?
I started with a simple var ErrPermissionNotAllowed = errors.New("permission not allowed")
. In my function I then wrap that using fmt.Errorf("%w: %v", ErrPermissionNotAllowed, failedPermissions)
. I can match this error using errors.Is(err, ErrPermissionNotAllowed)
. So far so good.
Now for display purposes I’d also like to access the individual permissions that could not be assigned. Parsing the error message is obviously not an option. So I thought, I create a custom error type, e.g. type PermissionNotAllowedError []Permission
and give it some func (e PermissionNotAllowedError) Error() string { return fmt.Sprintf("permission not allowed: %v", e) }
. My function would then return this error instead: PermissionNotAllowedError{failedPermissions}
At some layers I don’t care about the exact permissions that failed, but at others I do, at least when accessing them. A custom func (e PermissionNotAllowedError) Is(target err) bool
could match both the general ErrPermissionNotAllowed
as well as the PermissionNotAllowedError
. Same with As(…)
. For testing purposes the PermissionNotAllowedError
would then also try to match the included permissions, so assertions in tests would work nicely. But having two different errors for different matching seems not very elegant at all.
Did you ever encounter this scenario before? How did you address this? Is my thinking flawed?