Complete the code to create a basic exception filter class in NestJS.
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common'; @Catch() export class AllExceptionsFilter implements [1] { catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); response.status(500).json({ statusCode: 500, message: 'Internal server error', }); } }
The class must implement the ExceptionFilter interface to be a valid exception filter in NestJS.
Complete the code to catch only HTTP exceptions in the filter.
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'; @Catch([1]) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, message: exception.message, }); } }
The @Catch() decorator takes the exception type to catch. To catch HTTP exceptions only, use HttpException.
Fix the error in the catch method to correctly get the request object.
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.[1]();
const status = exception.getStatus();
response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}The ArgumentsHost method to get the request object is getRequest().
Fill both blanks to create a filter that catches multiple exception types.
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, BadRequestException } from '@nestjs/common'; @Catch([1], [2]) export class MultiExceptionFilter implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception instanceof HttpException ? exception.getStatus() : 500; response.status(status).json({ statusCode: status, message: exception.message || 'Unknown error', }); } }
The @Catch() decorator can take multiple exception classes to catch. Here, it catches HttpException and BadRequestException.
Fill all three blanks to create a custom exception filter that logs the error and sends a JSON response.
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, Logger } from '@nestjs/common'; @Catch([1]) export class LoggingExceptionFilter implements ExceptionFilter { private readonly logger = new [2](LoggingExceptionFilter.name); catch(exception: HttpException, host: ArgumentsHost) { this.logger.[3](exception.message); const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, message: exception.message, }); } }
The filter catches HttpException, uses the Logger class to create a logger instance, and calls the error method to log the exception message.