0
Faced the problem of getting errors from graphql in nest.js when the data does not pass validation. I wrote a global filter to bring it all to a single format, but it doesn’t want to work, or rather it works, but graphql wraps everything in a bunch of data and originalError
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
playground: false,
plugins: [ApolloServerPluginLandingPageLocalDefault()],
typePaths: ['./**/*.graphql'],
resolvers: { DateTime: GraphQLDateTime },
context: ({ req, res }) => ({ req, res }),
formatError: gqlErrorHandler,
}),
my gqlErrorHandler
import { GraphQLError } from 'graphql';
export const gqlErrorHandler = (error: GraphQLError) => {
return error;
};
I wrote a global filter to catch errors and format the output
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
@Catch()
export class AllExceptionsFilter<T> implements ExceptionFilter {
catch(exception: T, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
if (['graphql'].includes(host.getType())) {
throw new HttpException(
this._response(status, request, exception),
status,
);
}
response.status(status).json(this._response(status, request, exception));
}
private _response(status: number, request: Request, exception: any) {
return {
statusCode: status,
timestamp: new Date().toISOString(),
path: request?.url,
method: request?.method,
params: request?.params,
query: request?.query,
exception: {
name: exception['name'],
message: exception['message'],
},
};
}
}
I need to get errors in the form as in the screenshot
and I get this kind of rubbish
{
"data": {},
"errors": [
{
"message": "Http Exception",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"createArticle"
],
"extensions": {
"code": "BAD_REQUEST",
"stacktrace": [
"HttpException: Http Exception",
" at AllExceptionsFilter.catch (/usr/src/app/src/exceptions/all-exceptions.filter.ts:22:13)",
" at ExternalExceptionsHandler.invokeCustomFilters (/usr/src/app/node_modules/@nestjs/core/exceptions/external-exceptions-handler.js:34:32)",
],
"originalError": {
"statusCode": 400,
"exception": {
"name": "BadRequestException",
"message": "Bad Request Exception"
}
}
}
}
]
}
2 Answers
Reset to default
0
Are you using validation pipe?
If so, the actual error message detailing what you want (exactly what went wrong with the JSON that was sent in the request) is found within the response itself.
So basically, response.message instead of exception.message.
1
-
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
– Community
BotMay 3 at 7:31
0
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
playground: false,
plugins: [ApolloServerPluginLandingPageLocalDefault()],
typePaths: ['./**/*.graphql'],
resolvers: { DateTime: GraphQLDateTime },
context: ({ req, res }) => ({ req, res }),
formatError: (err) => ({ message: err.message, status: err.extensions.code }),
})
try this configure of graphQL