In my nestjs application, I am throwing BadReuqestException for one graphql endpoint. But in the response I still see 200 Ok
I tried throwing GraphQLError also but not working.
formatError: (error) => {
const originalError = error.extensions?.originalError;
if (!originalError) {
return {
message: error.message,
statusCode: error.extensions?.code,
};
}
return {
message: originalError['message'],
error: originalError['error'],
statusCode: originalError['statusCode'],
};
},
Custom exception handler
@Catch()
export class CustomExceptionFilter
implements ExceptionFilter, GqlExceptionFilter
{
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response: any = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const gqlHost = GqlArgumentsHost.create(host);
const info = gqlHost.getInfo<GraphQLResolveInfo>();
const status = exception.getStatus
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const errorResponse = {
statusCode: status,
timestamp: new Date().toLocaleDateString(),
error: exception.message || null,
};
// This is for REST petitions
if (request) {
const error = {
...errorResponse,
path: request.url,
method: request.method,
};
Logger.error(
`${request.method} ${request.url}`,
JSON.stringify(error),
'ExceptionFilter'
);
response.status(exception.getStatus()).json({
message: errorResponse.error,
statusCode: HttpStatus.BAD_REQUEST,
timestamp: errorResponse.timestamp,
});
} else {
// This is for GRAPHQL petitions
const error = {
...errorResponse,
type: info.parentType,
field: info.fieldName,
};
Logger.error(
`${info.parentType} ${info.fieldName}`,
JSON.stringify(error),
'ExceptionFilter'
);
response.status(exception.getStatus()).json({
message: errorResponse.error,
statusCode: status,
timestamp: errorResponse.timestamp,
});
// return exception;
return errorResponse;
}
}
}
Help me find a solution which I can use to send 400 as response status code 401 or any respective exception status. Note: In the response body status code is coming, but I want status code reflected in main status code where it's showing 200 Ok even if response body has 400 Bad Request.