Complete the code to import the Catch decorator from NestJS.
import { [1] } from '@nestjs/common';
The Catch decorator is imported from @nestjs/common to create exception filters.
Complete the code to apply the Catch decorator to an exception filter class.
@[1]() export class HttpExceptionFilter implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { // handle exception } }
The @Catch() decorator marks a class as an exception filter in NestJS.
Fix the error in the Catch decorator usage to catch only HttpException errors.
@Catch([1]) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { // handle HttpException } }
The @Catch() decorator can take exception types as arguments to catch specific exceptions like HttpException.
Fill both blanks to extract the response object and send a JSON error message inside the catch method.
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.[1]();
const response = ctx.[2]();
response.status(exception.getStatus()).json({
statusCode: exception.getStatus(),
message: exception.message
});
}Use host.switchToHttp() to get the HTTP context, then ctx.getResponse() to get the response object.
Fill the blanks to create a Catch decorator that catches both HttpException and QueryFailedError exceptions.
@Catch([1], [2]) export class DatabaseExceptionFilter implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); response.status(500).json({ statusCode: 500, error: exception.message }); } }
The @Catch() decorator can take multiple exception classes to catch. Here, HttpException and QueryFailedError are caught.