Custom errors
See original GitHub issueHi, I’m getting familiar with this library and am finding it very useful so far.
One thing I would like to be able to do is customize the default errors somewhat. It’s pretty straightforward to provide an error message when forbidding a single action using because
but in many cases it’s preferable to allow many actions for a user and base error messages on the user itself and not the user’s action when they are not authorized.
To give some background, we have a GraphQL API and we would like the flexibility to customize the default error messages in certain situations. One reason is so we can only call the throwUnlessCan
to authorize and not have to catch the error from throwUnlessCan
and then throw our own in each resolver. Another is that we want to be able to hide certain information from the users’ when appropriate (internal models or “subjects”, etc.)
Example:
// For every resolver we have an `authorize` function:
// We'd prefer to do this:
const authorize = async (root, args, context) => {
context.ability.throwUnlessCan('read', 'Post'); // throws custom error - Error('Not authorized!')
}
// instead of manually catching and then throwing for every resolver
const authorize = async (root, args, context) => {
try {
context.ability.throwUnlessCan('read', 'Post'); // catch default error
} catch(error) {
throw new Error('Not authorized!'); // throw our own custom error
}
}
I don’t see a way to achieve this currently but if I just missed it, let me know.
As far as I can tell, our needs could be met by allowing extension of the ForbiddenError and/or accepting a custom error via the AbilityBuilder/Ability constructor(s) that would be used in place of the static ForbiddenError here:
I’m happy to contribute toward this goal if needed.
Thanks for your help!
Issue Analytics
- State:
- Created 4 years ago
- Comments:14 (14 by maintainers)
Top GitHub Comments
available in
@casl/ability@3.4.0
Does the
because
ever stand on its own? I think the same thought process applies there so I’m not sure conveying meaning when splitting the functions is a big concern. How the functions are chained is a different problem but I think the library already relies on chaining functions that may not have individual meaning.I think you understand my needs:
throwUnlessCan
type of functionality). This is the most important request for me and seems like it should exist given thatbecause
exists in ability creation.As far as how these requests are met and how the API looks, you should be the one to decide since you’re the most familiar with the library. So whatever you think is best is good with me. 😃