The Catch decorator helps you handle errors in your NestJS application in a clean and organized way.
Catch decorator in NestJS
@Catch(exceptionFilter1, exceptionFilter2, ...)
export class YourExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
// handle the exception here
}
}The @Catch decorator marks a class as an exception filter.
You can specify which exceptions the filter should catch by passing them as arguments.
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
// handle all exceptions
}
}@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
// handle only HttpException
}
}@Catch(QueryFailedError, EntityNotFoundError)
export class DatabaseExceptionFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
// handle database related errors
}
}This example shows a simple exception filter that catches HttpException errors. It sends a JSON response with the status code, current time, request path, and error message.
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'; import { Request, Response } from 'express'; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse<Response>(); const request = ctx.getRequest<Request>(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, timestamp: new Date().toISOString(), path: request.url, message: exception.message || 'Error occurred', }); } }
Remember to bind your exception filter globally or to specific controllers to activate it.
You can create multiple filters for different error types to keep your code clean.
The Catch decorator marks a class as an error handler.
It helps catch specific or all exceptions in NestJS.
Use it to customize error responses and keep your code organized.
Practice
@Catch() decorator in NestJS?Solution
Step 1: Understand the role of
The@Catch()@Catch()decorator is used to mark a class as an exception filter in NestJS, which means it handles errors thrown in the application.Step 2: Differentiate from other decorators
Other decorators like route handlers or dependency injections serve different purposes, so@Catch()specifically relates to error handling.Final Answer:
To mark a class as an exception filter that handles errors -> Option AQuick Check:
Error handling =@Catch()[OK]
- Confusing @Catch() with route or middleware decorators
- Thinking @Catch() injects dependencies
- Assuming @Catch() handles normal requests
@Catch() decorator?Solution
Step 1: Understand
Using@Catch()usage without parameters@Catch()with no arguments means the filter will catch all exceptions.Step 2: Check other options
Options A, C, and D specify particular exception types, so they do not catch all exceptions.Final Answer:
@Catch()\nexport class AllExceptionsFilter implements ExceptionFilter { ... } -> Option AQuick Check:
No argument = catch all exceptions [OK]
- Passing incorrect exception types to @Catch()
- Using @Catch() with a non-error class
- Confusing @Catch() with middleware syntax
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' });
}
}Solution
Step 1: Analyze the exception filter behavior
The filter catches onlyNotFoundExceptionand sends a 404 status with a custom JSON message.Step 2: Understand the response sent
The response is explicitly set to status 404 with JSON { message: 'Resource not found' }, overriding default behavior.Final Answer:
HTTP response with status 404 and JSON { message: 'Resource not found' } -> Option DQuick Check:
Custom 404 JSON response = HTTP response with status 404 and JSON { message: 'Resource not found' } [OK]
- Assuming default error message is sent
- Thinking status 500 is returned
- Missing the JSON response in output
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');
}
}Solution
Step 1: Check method signature
Thecatchmethod's first parameterexceptionshould have a type annotation, typicallyunknownorany.Step 2: Verify other parts
The@Catch()decorator can be empty to catch all exceptions, returning void is allowed, and response retrieval is correct.Final Answer:
Theexceptionparameter lacks a type annotation -> Option BQuick Check:
Missing parameter type = Theexceptionparameter lacks a type annotation [OK]
- Forgetting to type the exception parameter
- Thinking @Catch() requires arguments
- Expecting catch to return a value
BadRequestException and UnauthorizedException with different custom messages. Which is the correct way to use the @Catch() decorator to achieve this?Solution
Step 1: Understand how to catch multiple exceptions
The@Catch()decorator accepts multiple exception classes as separate arguments to catch them in one filter.Step 2: Evaluate options
@Catch(BadRequestException, UnauthorizedException)\nexport class MultiExceptionFilter implements ExceptionFilter { ... } correctly passes multiple exceptions as separate arguments. @Catch([BadRequestException, UnauthorizedException])\nexport class MultiExceptionFilter implements ExceptionFilter { ... } incorrectly passes an array. @Catch()\nexport class MultiExceptionFilter implements ExceptionFilter { ... } catches all exceptions. Create two separate filters each with @Catch() for one exception uses multiple filters, not one.Final Answer:
@Catch(BadRequestException, UnauthorizedException)\nexport class MultiExceptionFilter implements ExceptionFilter { ... } -> Option CQuick Check:
Multiple exceptions as arguments = @Catch(BadRequestException, UnauthorizedException)\nexport class MultiExceptionFilter implements ExceptionFilter { ... } [OK]
- Passing exceptions as an array to @Catch()
- Using multiple filters instead of one
- Using empty @Catch() to catch specific exceptions
Ready to prove it?
Pass the test and this pattern moves unknown
