HttpException
The HttpException class is the base class for all HTTP-related errors in NestJS. Throwing it tells the framework exactly what status code and payload to send to the client.
Overview
If you throw a standard JavaScript Error (e.g., throw new Error('User not found')), NestJS doesn’t know what HTTP status code to associate with it, so it defaults to a generic 500 Internal Server Error.
By throwing an HttpException, you explicitly provide the HTTP status code (e.g., 404) and the message payload, allowing NestJS to gracefully handle the failure and inform the client correctly.
Key Concepts
- Constructor Arguments: It takes two required arguments: the
response(a string or an object) and thestatus(an HTTP status code number). - Base Class: All specific built-in exceptions (like
NotFoundExceptionorBadRequestException) inherit fromHttpException. - Global Handling: Nest’s default global exception filter automatically looks for
HttpExceptioninstances and serializes them into JSON.
Code Examples
Basic Usage
Throwing an exception with a simple string message and a status code.
import { Controller, Get, Param, HttpException, HttpStatus } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get(':id')
findOne(@Param('id') id: string) {
const user = null; // simulate database miss
if (!user) {
// Throw an HttpException with a 403 Forbidden status
throw new HttpException('You do not have access to this user', HttpStatus.FORBIDDEN);
}
return user;
}
}
The resulting JSON sent to the client:
{
"statusCode": 403,
"message": "You do not have access to this user"
}
Overriding the Entire Response Body
If you want to send a completely custom JSON structure instead of the default message/statusCode format, pass an object as the first argument.
@Get(':id')
findOne(@Param('id') id: string) {
throw new HttpException({
status: HttpStatus.BAD_REQUEST,
error: 'This is a custom error message',
context: {
userId: id,
attemptedAction: 'read'
}
}, HttpStatus.BAD_REQUEST);
}
The resulting JSON sent to the client:
{
"status": 400,
"error": "This is a custom error message",
"context": {
"userId": "123",
"attemptedAction": "read"
}
}
Best Practices
- Use
HttpStatusEnum: Never hardcode status codes like404or400. Always import and use theHttpStatusenum provided by@nestjs/common(e.g.,HttpStatus.NOT_FOUND). It makes the code much more readable. - Prefer Subclasses: While you can use
new HttpException('msg', HttpStatus.NOT_FOUND), you should almost always use the specific subclassnew NotFoundException('msg')instead. It’s cleaner and requires less typing. Use the baseHttpExceptiononly when you need to construct a highly dynamic response payload.