Performance: Exception filters
Exception filters affect the server response time and error handling flow, impacting how quickly errors are processed and sent to the client.
import { Catch, ExceptionFilter, ArgumentsHost, Logger } from '@nestjs/common'; @Catch() export class GlobalFilter implements ExceptionFilter { private readonly logger = new Logger(GlobalFilter.name); catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.status || 500; // Asynchronous logging without blocking setImmediate(() => this.logger.error(exception.message)); response.status(status).json({ message: exception.message }); } }
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 for (let i = 0; i < 1000000; i++) { /* heavy loop */ } response.status(status).json({ message: exception.message }); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous heavy processing in filter | 0 (server-side) | 0 (server-side) | 0 (server-side) | [X] Bad |
| Asynchronous logging in filter | 0 (server-side) | 0 (server-side) | 0 (server-side) | [OK] Good |
import { ExceptionFilter, Catch, ArgumentsHost, NotFoundException } from '@nestjs/common';
@Catch(NotFoundException)
export class NotFoundFilter implements ExceptionFilter {
catch(exception: NotFoundException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.status(404).json({ message: 'Resource not found' });
}
}import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
@Catch(HttpException)
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.status(500).json({ message: exception.message });
}
}Pass the test and this pattern moves unknown