I was recommended to request this from the graphcool forums- I am using graphql-yoga lambda to make my server. I love it, but I can鈥檛 quite figure out how to do errors. I currently have a function in context that will pull off the authorization jwt token and convert it to a user object. If the token is expired, I throw an error.
When I view it from graphQL playground, it has an error about how it can鈥檛 parse JSON. Is it possible to use a formatError function or afterware function to catch errors so that they will get sent back to the user correctly? Is this possibly a API gateway issue? (I鈥檓 using the serverless js framework for what it is worth.)
Here is a gist of how I actually do this.
I just wanted to add that I finally figured it out, so hopefully this can make it into the docs. The trick is to create a modified callback which gets passed into the graphQL Handler. When the function gets resolved, it will run through any code that you want.
Also, the type of lambda function is important- serverless sets up a proxy-lambda function by default which necessitates formatting the output like I do below and passing null as the error. This methodology should work for any error you want to throw in the lambda function- just include an error code number in the error and then search for it just like I searched for 401 below. Cheers!
exports.server = (event, context, callback) => {
const modifiedCallback = (error, output) => {
if (output.body.includes('401')) {
callback(null, {
statusCode: 401,
headers: { 'Content-Type': 'application/javascript' },
body: JSON.stringify({ message: 'Unauthorized' })
});
} else {
callback(error, output);
}
};
return lambda.graphqlHandler(event, context, modifiedCallback);
};
Is there a full example of how to use this? I currently have a very similar problem right now where I'd like to handle when an access token has expired that has been set in context.
Due to inactivity of this issue we have marked it stale. It will be closed if no further activity occurs.
Hey :wave:, It seems like this issue has been inactive for some time. In need for maintaining clear overview of the issues concerning the latest version of graphql-yoga we'll close it.
Feel free to reopen it at any time if you believe we should futher discuss its content. :slightly_smiling_face:
Most helpful comment
I just wanted to add that I finally figured it out, so hopefully this can make it into the docs. The trick is to create a modified callback which gets passed into the graphQL Handler. When the function gets resolved, it will run through any code that you want.
Also, the type of lambda function is important- serverless sets up a proxy-lambda function by default which necessitates formatting the output like I do below and passing null as the error. This methodology should work for any error you want to throw in the lambda function- just include an error code number in the error and then search for it just like I searched for 401 below. Cheers!