0
0
NestJSframework~5 mins

Custom exception classes in NestJS

Choose your learning style9 modes available
Introduction

Custom exception classes help you create clear and specific error messages in your NestJS app. They make your code easier to understand and fix.

When you want to send a specific error message for a certain problem in your app.
When you need to handle different errors differently in your controllers or services.
When you want to keep your error handling organized and reusable.
When you want to add extra information to errors beyond the default ones.
When you want to create user-friendly error responses for your API.
Syntax
NestJS
import { HttpException, HttpStatus } from '@nestjs/common';

export class CustomException extends HttpException {
  constructor(message: string) {
    super(message, HttpStatus.BAD_REQUEST);
  }
}

Extend HttpException to create your own error class.

Use super(message, statusCode) to set the error message and HTTP status.

Examples
This creates a custom exception for 404 errors with a fixed message.
NestJS
import { HttpException, HttpStatus } from '@nestjs/common';

export class NotFoundException extends HttpException {
  constructor() {
    super('Resource not found', HttpStatus.NOT_FOUND);
  }
}
This custom exception sends a message plus a list of validation errors.
NestJS
import { HttpException, HttpStatus } from '@nestjs/common';

export class ValidationException extends HttpException {
  constructor(errors: string[]) {
    super({ message: 'Validation failed', errors }, HttpStatus.BAD_REQUEST);
  }
}
Sample Program

This example shows a custom exception class and a filter that catches it. When you visit the '/error' route, it throws the custom error and returns a JSON response with status 403 and the message.

NestJS
import { Controller, Get, UseFilters } from '@nestjs/common';
import { HttpException, HttpStatus, ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

// Custom exception class
export class MyCustomException extends HttpException {
  constructor() {
    super('This is a custom error', HttpStatus.FORBIDDEN);
  }
}

// Exception filter to catch custom exception
@Catch(MyCustomException)
export class MyCustomExceptionFilter implements ExceptionFilter {
  catch(exception: MyCustomException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(exception.getStatus()).json({
      statusCode: exception.getStatus(),
      message: exception.message
    });
  }
}

@Controller()
@UseFilters(MyCustomExceptionFilter)
export class AppController {
  @Get('error')
  throwError() {
    throw new MyCustomException();
  }
}
OutputSuccess
Important Notes

Always extend HttpException for HTTP errors in NestJS.

Use exception filters to customize how errors are sent to clients.

Custom exceptions improve code clarity and API responses.

Summary

Custom exception classes let you create specific error messages.

They extend HttpException and set message and status.

Use filters to handle and format these exceptions in your app.