NestJS exception handling basics and how to create custom exceptions

Learn the basics of exception handling in NestJS and how to create custom exceptions.

overview

NestJS provides an exception layer for handling unhandled exceptions throughout your application. By using this exception layer, you can automatically return an appropriate response even if an unhandled exception occurs.

NestJS controllers are responsible for receiving HTTP requests from clients and returning appropriate responses. This article details how to create controllers in NestJS to handle HTTP methods such as GET, POST, PUT, and DELETE.

nest.js v10.1.7
nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

How to throw an exception

NestJS provides a default error class named HttpException. This error class can be imported from the @nestjs/common package. Throwing an HttpException tells NestJS that an error has occurred and allows it to generate an appropriate error response.

Below is an example of a controller that throws an HttpException.

import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  getUsers(): User[] {
    return this.usersService.getUsers();
  }
  @Post()
  addUser(@Body() name: string): void {
    this.usersService.addUser(name);
  }
  @Put(':id')
  putUser(@Param('id') id: number, @Body('name') name: string): void {
    this.usersService.putUser(id, name);
  }
  @Delete(':id')
  deleteUser(@Param('id') id: number): void {
    this.usersService.deleteUser(id);
  }
  @Get('throw')
  getException(): string {
    throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
  }
}

The code above throws an HttpException when a GET request to /users/throw comes. This exception has the message ‘Forbidden’, with status code 403 (Forbidden).

test

curl http://localhost:3000/users/throw

How to throw custom exceptions

NestJS also allows you to create custom exceptions that inherit from HttpException. You can throw exceptions with application-specific error information by creating custom exceptions.

Below is an example of creating and throwing a custom exception.

/src/users/exception/forbidden.exception.ts

import { HttpException, HttpStatus } from '@nestjs/common';

export class ForbiddenException extends HttpException {
  constructor() {
    super('Custom Forbidden', HttpStatus.FORBIDDEN);
  }
}

/src/users/users.controller.ts

import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { ForbiddenException } from './exceptions/forbidden.exception';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  getUsers(): User[] {
    return this.usersService.getUsers();
  }

  @Post()
  addUser(@Body() name: string): void {
    this.usersService.addUser(name);
  }

  @Put(':id')
  putUser(@Param('id') id: number, @Body('name') name: string): void {
    this.usersService.putUser(id, name);
  }

  @Delete(':id')
  deleteUser(@Param('id') id: number): void {
    this.usersService.deleteUser(id);
  }
  @Get('throw')
  getException(): string {
    throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
  }
  @Get('custom_throw')
  getCustomException(): string {
    throw new ForbiddenException();
  }
}

The above code creates a custom exception called ForbiddenException and throws it when a GET request to /users/custom comes.

test

curl http://localhost:3000/users/custom_throw

summary

NestJS provides an exception layer that automatically handles unhandled exceptions. You can also throw exceptions easily by using HttpException. Additionally, by creating custom exceptions that inherit from HttpException, it is possible to throw exceptions with application-specific error information. By using these functions, error handling can be performed efficiently.