There are different ways to approach this, but some possible solutions for correcting error output format in Nest.js + GraphQL are:
import { Catch, ExceptionFilter, ArgumentsHost } from '@nestjs/common';
import { GqlExceptionFilter, GqlArgumentsHost } from '@nestjs/graphql';
@Catch()
export class GraphqlErrorInterceptor implements GqlExceptionFilter {
catch(error: Error, host: ArgumentsHost) {
const gqlHost = GqlArgumentsHost.create(host);
const ctx = gqlHost.getContext();
const statusCode = error['status'] || 500;
const message = error.message || 'Internal server error';
const code = error['code'] || null;
return {
message,
code,
statusCode,
};
}
}
This interceptor can be used in the app module like this:
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { GraphqlErrorInterceptor } from './graphql-error.interceptor';
@Module({
providers: [
{
provide: APP_FILTER,
useClass: GraphqlErrorInterceptor,
},
],
})
export class AppModule {}
import { graphqlErrors } from 'graphql-errors';
graphqlErrors.init({
errors: {
BadRequest: {
message: 'The request was invalid',
statusCode: 400,
},
Unauthorized: {
message: 'You are not authorized to perform this operation',
statusCode: 401,
},
NotFound: {
message: 'The resource was not found',
statusCode: 404,
},
},
});
// Example usage in a resolver
@Resolver('User')
export class UserResolver {
@Query()
async getUserById(@Args('id') id: string) {
const user = await this.userService.findById(id);
if (!user) {
graphqlErrors.throw('NotFound', `User not found with id ${id}`);
}
return user;
}
}
This would result in a formatted error response like this:
{
"data": null,
"errors": [
{
"message": "User not found with id 123",
"extensions": {
"code": "NotFound",
"statusCode": 404
}
}
]
}
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
catch(error: Error, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const statusCode = error instanceof HttpException
? error.getStatus()
: 500; // default status code
const message = error.message || 'Internal server error';
response.status(statusCode).json({
statusCode,
message,
error: {
name: error.name,
stack: error.stack,
// other error details if needed
},
});
}
}
This filter can ... (more)
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-03-28 11:00:00 +0000
Seen: 12 times
Last updated: Jan 26 '22
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?
How can we require users to be logged in before they can access the root folders in WordPress?
In SCSS, what is the method for grouping and reusing a set of classes and styles?
How can popen() be used to direct streaming data to TAR?
How does iOS retrieve information from a BLE device?
How can Django Admin accommodate a variety of formats and locales for its input fields?