Can someone help me understand how to throw authentication errors in a graphQL lambda app? I'm using graphQL-yoga with serverless and I can authenticate a request and either return a user that I get from the jwt, a {}
for no token, or throw an authentication error if the token is old. When I throw an error it gets caught in the catch statement of my authenticate block, but I have no idea how to actually return that from the lambda.
const lambda = new GraphQLServerLambda({
typeDefs,
context: ({ event, context }) =>
authenticate(event.headers.Authorization)
.then(user => ({ db: mainDb, user}))
.catch(e => {
console.log('Caught the auth error here');
throw e;
}),
Query: { \\ some queries here.... },
Mutation: { \\ some mutations here...}
});
How can I either format the error or throw it from the right spot so that I get an actual formatted error? Instead I get a Unexpected token I in JSON...
error in the client. Clearly I need to do some sort of formatting during my throw
but it isn't totally obvious to me how to do that.
If it is helpful, here in my exports part. I'm trying everything from try/catch to then/catch and at this point I have seemed to already miss catching the error. Is there a better way to be doing this? The main thing I need is the ability to either authenticate, reject bad tokens, and otherwise just return a {}
for a non-logged in user. I'm having the hardest time finding custom authorizers that allow non-logged in users so that's why I am doing the auth directly in my graphQL endpoint
exports.server = (event, context, callback) => {
try {
return lambda
.graphqlHandler(event, context, callback)
.then(b => b)
.catch(e => console.log(`can't catch it here ${e}`));
} catch (e) {
console.log('or here');
callback(e);
}
};