Complete the code to create a global exception filter class in NestJS.
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common'; @Catch() export class GlobalExceptionFilter implements [1] { catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); response.status(500).json({ message: 'Internal server error' }); } }
The class must implement the ExceptionFilter interface to act as an exception filter in NestJS.
Complete the code to apply the global exception filter in the main bootstrap function.
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { GlobalExceptionFilter } from './filters/global-exception.filter'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.[1](new GlobalExceptionFilter()); await app.listen(3000); } bootstrap();
To apply a global exception filter, use the useGlobalFilters method on the app instance.
Fix the error in the global exception filter to correctly get the HTTP response object.
catch(exception: any, host: ArgumentsHost) {
const ctx = host.[1]();
const response = ctx.getResponse();
response.status(500).json({ message: 'Internal server error' });
}To get the HTTP context from ArgumentsHost, use the switchToHttp() method.
Fill both blanks to create a global exception filter that returns the exception message and status code.
catch(exception: any, host: ArgumentsHost) {
const ctx = host.[1]();
const response = ctx.getResponse();
const status = exception.[2] || 500;
response.status(status).json({
statusCode: status,
message: exception.message || 'Internal server error',
});
}Use switchToHttp() to get the HTTP context and access the status property from the exception for the HTTP status code.
Fill all three blanks to create a global exception filter that logs the error and sends a JSON response with status and message.
catch(exception: any, host: ArgumentsHost) {
const ctx = host.[1]();
const response = ctx.getResponse();
const request = ctx.getRequest();
const status = exception.[2] || 500;
console.error('Error:', exception.message);
response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.[3],
message: exception.message || 'Internal server error',
});
}Use switchToHttp() to get HTTP context, status property from exception for status code, and url property from request for the request path.