Node.js Framework Series — 1.2.6. NestJS — Exceptions
NestJS comes with really strong exception management structures called Exception Filters. With this built-in exception management layer, we can handle all of the unhandled exceptions across the NestJS application. Therefore, if you don’t handle any exception in your code, it is caught by a built-in global exception filter, which handles exceptions of type HttpException. So, when exception is unrecognised, it generates the following default JSON response:
{
"statusCode": 500,
"message": "Internal server error"
}
The usage of NestJS Exception filters are quite simple. Let’s have a look at it with a simple example as shown below:
notification.service.ts
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { NotificationPool } from './interface/notification-pool.interface';@Injectable()
export class NotificationService {
findAll(): NotificationPool[] {
throw new HttpException('Unauthorized request', HttpStatus.UNAUTHORIZED);
}
}
And the response will be as follows:
{
"statusCode": 401,
"message": "Unauthorized"
}
NestJS also provides a response overriding as follows:
findAll(): NotificationPool[] {
throw new HttpException(
{
status: HttpStatus.UNAUTHORIZED,
error: 'This is a custom message for unauthorized request',
},
HttpStatus.UNAUTHORIZED,
);
}
NestJS Exception filters supports custom exceptions as well. We will talk about exception filters in the following chapters, too.