Как отформотировать вывод исключений в grapql и nest.js
подключаю graphql в nest.js
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
playground: false,
plugins: [ApolloServerPluginLandingPageLocalDefault()],
typePaths: ['./**/*.graphql'],
resolvers: { DateTime: GraphQLDateTime },
context: ({ req, res }) => ({ req, res }),
formatError: gqlErrorHandler,
}),
gqlErrorHandler
import { GraphQLError } from 'graphql';
export const gqlErrorHandler = (error: GraphQLError) => {
if ('response' in error.extensions) {
const { message, ...response } = error.extensions['response'] as {
message: string;
extensions: any;
};
return {
message,
extensions: {
timestamp: new Date().toISOString(),
...response,
},
};
}
return error;
};
глобальный exception
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'],
},
};
}
}
мне нужно получать ошибки в таком виде как на скрине
а я получаю вот такой вот хлам
{
"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)",
" at ExternalExceptionsHandler.next (/usr/src/app/node_modules/@nestjs/core/exceptions/external-exceptions-handler.js:13:29)",
" at Object.createArticle (/usr/src/app/node_modules/@nestjs/core/helpers/external-proxy.js:14:42)",
" at processTicksAndRejections (node:internal/process/task_queues:95:5)"
],
"originalError": {
"statusCode": 400,
"timestamp": "2023-03-29T17:19:30.105Z",
"exception": {
"name": "BadRequestException",
"message": "Bad Request Exception"
}
}
}
}
]
}
