errorHandler not handling global resolver errors/exceptions? #709
-
Hi There, Is global error supposed to catch unhandled errors/exception from resolvers? I don't want to handle errors in every resolver itself and trying to handle that and log in a global handler for the graphql operations, but for some reason the The code below shows how I am registering the error Handler, therefore I can confirm that is not being called: app.register(mercurius, {
path: options.path,
routes: true,
defineMutation: true,
errorHandler: (
error: MercuriusError,
request: FastifyRequest,
reply: FastifyReply
) => {
// I can confirm this code is not being executed by debugging it and also adding a thumb code like throw new Error("test");
reply.send({
data: null,
errors: [
{
message: error.message,
code: error.code,
},
],
});
}, Also another question is about what is the recommended way to access the context inside the error handler as I am planning to log custom errors using this function. Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
You have to handle all errors in your resolvers, it's how you prevent all sort of problems. Note that this concept is true for all Node.js code and not specific to Mercurius. Could you upload an example to reproduce your problem? So we can help you. |
Beta Was this translation helpful? Give feedback.
-
Hey @mcollina , I hope you are well! Thank you very much for the quick response. I actually handle expected errors on all resolvers, therefore for unexpected errors I would like to log it and return a custom generic response e.g, Sorry, something went wrong, please try again.... bla bla bla. So instead of doing that for every resolver I thought of delegating this to a global error handler. The main goal is to avoid adding a generic error handler that produces the same output for every single resolver in the code Here is the resolver code try {
//resolver stuff...
}
catch (error) {
if(error.code === 'knownError') return handleError(err);
//this error was unexpected.
throw error;
} Here is the errorHandler code: app.register(mercurius, {
path: options.path,
routes: true,
defineMutation: true,
errorHandler: (
error: MercuriusError,
request: FastifyRequest,
reply: FastifyReply
) => {
//every unhandled/unexpected error would fall into this method.
//I would grab the graphql context/logger service and log the error and return a custom exception
reply.send({
data: null,
errors: [
{
message: error.message,
code: error.code,
},
],
});
},
|
Beta Was this translation helpful? Give feedback.
You have to handle all errors in your resolvers, it's how you prevent all sort of problems. Note that this concept is true for all Node.js code and not specific to Mercurius.
Could you upload an example to reproduce your problem? So we can help you.