Performance: Global exception filters
Global exception filters affect the response time and error handling flow, impacting interaction responsiveness and server response speed.
import { Catch, ExceptionFilter, ArgumentsHost } from '@nestjs/common'; @Catch() export class GlobalFilter implements ExceptionFilter { async catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.status || 500; // Use async non-blocking logging await asyncLogging(exception); response.status(status).json({ message: 'Error occurred' }); } }
import { Catch, ExceptionFilter, ArgumentsHost } from '@nestjs/common'; @Catch() export class GlobalFilter implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.status || 500; // Synchronous heavy logging or blocking operation here heavySyncLogging(exception); response.status(status).json({ message: 'Error occurred' }); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous blocking logging in global filter | 0 (server-side) | 0 (server-side) | 0 (server-side) | [X] Bad |
| Asynchronous non-blocking logging in global filter | 0 (server-side) | 0 (server-side) | 0 (server-side) | [OK] Good |
main.ts file of a NestJS app?useGlobalFilters() on the app instance.new before passing it to useGlobalFilters().import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
if (exception instanceof HttpException) {
const status = exception.getStatus();
response.status(status).json({ message: exception.message });
} else {
response.status(500).json({ message: 'Internal server error' });
}
}
}import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
@Catch()
export class MyFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const response = host.getResponse();
response.status(400).json({ error: 'Bad Request' });
}
}host.switchToHttp().getResponse(), not host.getResponse().catch method?Pass the test and this pattern moves unknown