0
0
NestJSframework~5 mins

Built-in HTTP exceptions in NestJS

Choose your learning style9 modes available
Introduction

Built-in HTTP exceptions help you send clear error messages to users when something goes wrong in your app. They make error handling simple and consistent.

When a user tries to access a resource that does not exist.
When a user sends invalid data to your API.
When a user is not authorized to perform an action.
When the server encounters an unexpected error.
When you want to inform the client about request limits or forbidden actions.
Syntax
NestJS
throw new HttpException('Error message', HttpStatus.STATUS_CODE);
You can use specific exceptions like NotFoundException or BadRequestException instead of HttpException for common cases.
HttpStatus.STATUS_CODE is a number like 404 for Not Found or 400 for Bad Request.
Examples
This sends a 404 error with a message 'User not found'.
NestJS
throw new NotFoundException('User not found');
This sends a 400 error when the user sends wrong data.
NestJS
throw new BadRequestException('Invalid input data');
This sends a 403 error with a custom message.
NestJS
throw new HttpException('Forbidden access', HttpStatus.FORBIDDEN);
Sample Program

This controller has a route to get a user by ID. If the user is not found, it throws a built-in NotFoundException. This sends a 404 error with a clear message to the client.

NestJS
import { Controller, Get, Param, NotFoundException } from '@nestjs/common';

@Controller('users')
export class UsersController {
  private users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];

  @Get(':id')
  getUser(@Param('id') id: string) {
    const user = this.users.find(u => u.id === Number(id));
    if (!user) {
      throw new NotFoundException(`User with id ${id} not found`);
    }
    return user;
  }
}
OutputSuccess
Important Notes

Use built-in exceptions to keep your API responses consistent and easy to understand.

You can create custom exceptions by extending HttpException if you need special behavior.

Summary

Built-in HTTP exceptions help handle errors clearly and simply.

Use specific exceptions like NotFoundException for common HTTP errors.

Throw exceptions to send proper HTTP status codes and messages to clients.