Discover how a simple decorator can save you from endless error-handling headaches!
Why Catch decorator in NestJS? - Purpose & Use Cases
Imagine writing code to handle errors in every function manually, like wrapping each call in try-catch blocks everywhere in your NestJS app.
Manually catching errors everywhere makes code messy, repetitive, and easy to forget, leading to bugs and inconsistent error handling.
The Catch decorator lets you cleanly and consistently handle errors by marking classes, so NestJS automatically manages exceptions for you.
try {
await this.service.doSomething();
} catch (error) {
handleError(error);
}@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
handleError(exception);
}
}It enables centralized, clean, and reusable error handling that keeps your code simple and reliable.
In a REST API, using the Catch decorator helps return consistent error responses without cluttering every controller method with try-catch blocks.
Manual error handling is repetitive and error-prone.
Catch decorator centralizes and simplifies error management.
It keeps your NestJS code clean and consistent.
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
