Fallback exception filter is mean to catch any exception which are not catched by other exception filters;
import { Catch, ExceptionFilter, ArgumentsHost } from "@nestjs/common";
@Catch()
export class FallbackExpectionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
console.log('fallback exception handler triggered',
JSON.stringify(exception));
const ctx = host.switchToHttp();
const response = ctx.getResponse();
return response.status(500)
.json({
statusCode: 500,
createdBy: "FallbackExceptionFilter",
errorMessage: exception.message ? exception.message: 'Unexpected error ocurred';
});
}
}
main.ts:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './filters/http-exception.filter';
import { FallbackExpectionFilter } from './filters/fallback.filter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.useGlobalFilters(
new FallbackExpectionFilter(),
new HttpExceptionFilter(),
);
await app.listen(9000);
}
bootstrap();
Order matters, from most generic to specific.