I'm trying to achieve a simple behavior: Whenever an exception is thrown I would like to send the error as a response. My kind of naive code looks like this, but doesn't respond at all:
Exception Filter:
import { ExceptionFilter, ArgumentsHost, Catch } from '@nestjs/common';
@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
return JSON.stringify(
{
error: exception,
},
null,
4,
);
}
}
Module
@Module({
imports: [],
controllers: [AppController, TestController],
providers: [AppService, AnyExceptionFilter],
})
export class AppModule {}
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new AnyExceptionFilter());
await app.listen(1212);
}
bootstrap();
Is there anything I miss? Thanks in advance :)
import { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';
@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
catch(error: Error, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
const status = (error instanceof HttpException) ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
response
.status(status)
.json(error);
}
}
This code seems to be working fine for me.
Nest version: 5.0.1
Just adding a bit more info about the previous answers. The suggested code provided by @oto-meskhy here is (replicating it just for completion purposes - credits to @oto-meskhy):
import { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';
@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
catch(error: Error, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
const status = (error instanceof HttpException) ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
response
.status(status)
.json(error);
}
}
This code should work IF your NestJS application didn't defined a specific platform in the NestFactory.create()
method. HoweHowever, if the chosen platform is Fastify
(docs here), note that the a small piece of the code above will not work, more specifically:
...
response
.status(status)
.send(object)
In such case, your application code should change a little bit to use Fastify
's Reply methods, like this:
// fastify
response
.code(status)
.send(error);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With