Performance: Catch decorator
This affects how errors are handled during request processing, impacting response time and user experience.
import { Catch, ExceptionFilter, ArgumentsHost } from '@nestjs/common'; @Catch() export class GlobalCatch implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); // offload heavy work asynchronously setImmediate(() => { // logging or cleanup }); response.status(500).json({ message: 'Internal error' }); } }
import { Catch, ExceptionFilter, ArgumentsHost } from '@nestjs/common'; @Catch() export class GlobalCatch implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { // heavy synchronous processing or logging for (let i = 0; i < 1000000; i++) { /* expensive loop */ } const ctx = host.switchToHttp(); const response = ctx.getResponse(); response.status(500).json({ message: 'Internal error' }); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous heavy work in Catch decorator | Minimal | 0 | Blocks main thread delaying paint | [X] Bad |
| Asynchronous error handling with deferred work | Minimal | 0 | Non-blocking, smooth paint and interaction | [OK] Good |
@Catch() decorator in NestJS?@Catch()@Catch() decorator is used to mark a class as an exception filter in NestJS, which means it handles errors thrown in the application.@Catch() specifically relates to error handling.@Catch() [OK]@Catch() decorator?@Catch() usage without parameters@Catch() with no arguments means the filter will catch all exceptions.NotFoundException is thrown?import { Catch, ExceptionFilter, ArgumentsHost, NotFoundException } from '@nestjs/common';
@Catch(NotFoundException)
export class NotFoundFilter implements ExceptionFilter {
catch(exception: NotFoundException, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
response.status(404).json({ message: 'Resource not found' });
}
}NotFoundException and sends a 404 status with a custom JSON message.import { Catch, ExceptionFilter, ArgumentsHost } from '@nestjs/common';
@Catch()
export class MyFilter implements ExceptionFilter {
catch(exception, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.status(500).send('Internal Server Error');
}
}catch method's first parameter exception should have a type annotation, typically unknown or any.@Catch() decorator can be empty to catch all exceptions, returning void is allowed, and response retrieval is correct.exception parameter lacks a type annotation -> Option Bexception parameter lacks a type annotation [OK]BadRequestException and UnauthorizedException with different custom messages. Which is the correct way to use the @Catch() decorator to achieve this?@Catch() decorator accepts multiple exception classes as separate arguments to catch them in one filter.Pass the test and this pattern moves unknown