Comments (5)
@dakshshah96 Sure!
Example you have a "validation" resolver:
Resolver A: validateAuthObject
const { AuthorizationError } = require("../../errors"); // -- This is an instance of `apollo-errors`
module.exports = async (root, args, context, info) => {
const user = _.get(args, "user", null);
if (!user) {
throw new AuthorizationError({
message: "Missing user object.",
data: {
code: "auth-1"
}
});
}
};
In your main resolver of a certain GraphQL query, let say getData(user: User, options: JSON!)
. We combine our validateUserObject
and the "main" resolver.
const { combineResolvers } = require("graphql-resolvers");
getData: combineResolvers(validateUserObject, async (obj, args, context, info) => {
const options = _.get(args, "options", {});
return DataRepository.getAll(options);
}),
Once user
is null
it will return t
{
"data": null,
"errors": [
{
"message": "Missing user object.",
"name": "AuthorizationError",
"time_thrown": "2018-03-22T10:48:42.113Z",
"data": {
"code": "auth-1"
}
}
]
}
Another approach is without the need for an extra resolver (if there's no need for reusability). Let's use your code here as an example:
const { UnknownError } = require('../../../helpers/errors')
const createAdmin = async (payload) => {
try {
const { error, value } = Joi.validate(payload, adminReqSchema)
if (error) {
throw new UnknownError({
data: {
reason: 'Schema validation error'
}
})
}
const admin = await new Admin({ name: value.name, phoneNumber: value.phoneNumber }).save()
await new Auth({ userId: admin._id, role: 'admin', password: value.password }).save()
return admin
} catch (err) {
console.log(err)
throw err; // -- Re-throwing the error will allow GraphQL to immediately format the error as an `UnknownError` and will populate the `errors` field.
}
}
I hope this helps. :)
from graphql-shield.
@jhnferraris custom errors are currently not supported, but I would love to hear more from you on this topic. Could you add this to roadmap
thread? 🙂
from graphql-shield.
@maticzav Any updates on this? I really want my developers to know what the cause of the error is. For example, JWT token has expired
or something like Authorization header is required
instead of just Insufficient Permissions.
.
from graphql-shield.
Since it is still in their roadmap, we opted on using a different approach. We used graphql-resolvers's, combineResolvers
. In which we have one resolver doing the "validation" and throw custom error when the validation fails.
from graphql-shield.
@jhnferraris If it's not too much trouble, can you give me an example of how custom errors can be implemented? I've already defined all of my schema using graphql-tools
in my apollo-server
powered GraphQL backend. Thanks!
from graphql-shield.
Related Issues (20)
- Add the ability to use Fragments and post-execution rules with the single server/schema
- Add Typescript typings to rule args
- Add the ability to attach rules using GraphQL Directives
- CI: add codecov reports
- Provide a way to expose authorization metadata through the graphql schema
- GraphQL Shield Roadmap HOT 1
- 7.6.4 ESM build broken HOT 5
- Documentation website down HOT 1
- How to use `if` condition in GraphQL Shield HOT 2
- Shield rules type generation based on schema HOT 1
- Feature request: wildcard functionality for field names
- Update [email protected] module to avoid @types/lodash and babel runtime in production deps
- fallbackError loses custom error types
- fallbackRule context information HOT 2
- Question: Is there a way to return objects on rules?
- ..
- Typo in the Docs
- Shield permissions only working properly with 'debug: true' HOT 1
- Performance -- every field wrapped is unnecessarily wrapped in a promise HOT 1
- Documents are not populated when running `graphql-shield`, thus leading to `undefined` permission errors.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from graphql-shield.