Sobes.tech
Junior — Middle

How is exception and error handling implemented within NestJS?

sobes.tech AI

Answer from AI

In NestJS, exception handling is implemented through the exception filters mechanism. By default, if an error occurs in a controller or service, NestJS returns a standard HTTP response with an error code.

To customize error handling, you can create a class that implements the ExceptionFilter interface and override the catch(exception, host) method. In this method, you can handle the error, for example, log it and return a custom response.

Example of a simple exception filter:

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpErrorFilter 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,
    });
  }
}

This filter can be applied globally or at the controller/method level.

Additionally, for handling unexpected errors, you can use a global filter that catches all exceptions (@Catch() without parameters).

NestJS also supports built-in error handling through built-in exceptions (HttpException and its subclasses), which are automatically converted into HTTP responses with the appropriate status.