'how to handle errors in exception filters with Fastify NestJs?
Im using the following code to catch error in fastify, however my error is that "response.send" is not a function:
What's the right way to send the error on my global exception filters using that structure in Fastify?
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
Injectable,
} from '@nestjs/common';
import dotenv from 'dotenv';
import { FastifyReply, FastifyRequest } from 'fastify';
@Catch()
@Injectable()
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const context = host.switchToHttp();
const response: FastifyReply<any> = context.getResponse<FastifyReply>();
const request: FastifyRequest = context.getRequest<FastifyRequest>();
let status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const message =
exception instanceof Error ? exception.message : exception.message.error;
response.send({"test":"test"})
}
}
Solution 1:[1]
You should add the exception at catch decorator, ie @Catch(HttpException)
,and without injectable decorator. My snippet for custom http-exception-filter is like below and it works. Hope this help.
@Catch(HttpException)
export class HttpExceptionFilter<T extends HttpException> implements ExceptionFilter
{
catch(exception: T, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response: FastifyReply<any> = ctx.getResponse<FastifyReply>();
const status = exception.getStatus();
const exceptionResponse = exception.getResponse();
const error =
typeof response === 'string'
? { message: exceptionResponse }
: (exceptionResponse as object);
response
.status(status)
.send({ ...error, timestamp: new Date().toISOString() });
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cipto HD |