bug
This commit is contained in:
@@ -1,26 +1,55 @@
|
||||
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, ExecutionContext } from '@nestjs/common';
|
||||
import { GqlExecutionContext } from '@nestjs/graphql';
|
||||
import { FastifyReply } from 'fastify';
|
||||
|
||||
@Catch(HttpException)
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: HttpException, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const reply = ctx.getResponse<FastifyReply>();
|
||||
// const request = ctx.getRequest<FastifyRequest>();
|
||||
const status = exception.getStatus() || HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
// Check if this is a GraphQL context
|
||||
if (host.getType<'graphql' | 'http'>() === 'graphql') {
|
||||
try {
|
||||
// In GraphQL context, host is actually an ExecutionContext
|
||||
const gqlContext = GqlExecutionContext.create(host as ExecutionContext);
|
||||
if (gqlContext && gqlContext.getInfo()) {
|
||||
console.log('GraphQL context**');
|
||||
// For GraphQL, let the exception propagate - GraphQL will handle it automatically
|
||||
// We can't use HTTP response methods in GraphQL context
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Not a GraphQL context, continue with HTTP handling
|
||||
}
|
||||
}
|
||||
|
||||
const exceptionResponse = exception.getResponse();
|
||||
const message = this.extractMessage(exceptionResponse);
|
||||
// Handle HTTP/REST context
|
||||
try {
|
||||
const ctx = host.switchToHttp();
|
||||
const reply = ctx.getResponse<FastifyReply>();
|
||||
|
||||
reply.status(status).send({
|
||||
statusCode: status,
|
||||
success: false,
|
||||
error: {
|
||||
message,
|
||||
// timestamp: new Date().toISOString(),
|
||||
// path: request.url,
|
||||
},
|
||||
});
|
||||
// Safety check: ensure reply has the status method
|
||||
if (!reply || typeof reply.status !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
// const request = ctx.getRequest<FastifyRequest>();
|
||||
const status = exception.getStatus() || HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
|
||||
const exceptionResponse = exception.getResponse();
|
||||
const message = this.extractMessage(exceptionResponse);
|
||||
|
||||
reply.status(status).send({
|
||||
statusCode: status,
|
||||
success: false,
|
||||
error: {
|
||||
message,
|
||||
// timestamp: new Date().toISOString(),
|
||||
// path: request.url,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// If we can't handle it, let it propagate
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private extractMessage(response: string | Record<string, any>): string | string[] {
|
||||
|
||||
Reference in New Issue
Block a user