NestJS is a progressive, Node.js framework for building efficient and scalable server-side applications. One of the key advantages of NestJS is its powerful dependency injection system and modular structure, which makes building enterprise-level applications more manageable.
In this article, we will explore how error handling works in NestJS and common strategies for managing exceptions
Understanding Error Handling in NestJS
Error handling in NestJS revolves around exceptions. In NestJS, errors are treated as exceptions, and the framework has a built-in exception-handling system to deal with these errors. When an error occurs, it is either thrown or caught within the system, and NestJS provides mechanisms to customize the way these exceptions are handled.
NestJS has a default error-handling mechanism that catches unhandled exceptions and sends appropriate responses, but it also allows developers to extend and customize the handling process based on the specific needs of the application.
Setting Up NestJS Application For Error Handling
Step 1: Ensure you have Node.js and npm installed
You can download and install from the site of the node.js
node --version
npm --version
Step 2: Install NestJS CLI
If you haven't already, install the NestJS CLI globally using npm:
npm install -g @nestjs/cli
Step 3: Create a new NestJS Project
If you don't have a project yet, create one using the CLI and add the project file to the terminal.
nest new my-nest-project
cd my-nest-project
Step 4: Run the application
Use the following command to start your NestJS application.
npm run start
Folder Structure
Folder StructureDependencies
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}
Various Approaches for Error Handling in NestJS
Approach 1: Built-in Exception Filters
NestJS gives integrated exception filters, like HttpException, which can help you throw commonplace HTTP errors consisting of 404, 400, 500, and etc.
Syntax:
throw new HttpException('Error Message', HttpStatus.BAD_REQUEST);
Example:
JavaScript
//my-nest-project\src\example.controller.ts
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
@Controller('example')
export class ExampleController {
@Get()
getExample() {
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}
}
JavaScript
//.\my-nest-project\src\app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ExampleController } from './example.controller';
@Module({
imports: [],
controllers: [AppController, ExampleController],
providers: [AppService],
})
export class AppModule { }
Output:
Built-in Exception FiltersApproach 2: Custom Exception Filters
Custom exception filters assist you to manage exceptions in a custom way via extending the ExceptionFilter class and implementing the seize approach.
Example:
JavaScript
//.\nest2\src\cats\custom-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch(HttpException)
export class CustomExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();
const message = exception.message;
response
.status(status)
.json({
statusCode: status,
message: message,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
JavaScript
//.\nest2\src\cats\cats.controller.ts
import { Controller, Get, HttpException, HttpStatus, UseFilters } from '@nestjs/common';
import { CustomExceptionFilter } from './custom-exception.filter';
@Controller('cats')
@UseFilters(CustomExceptionFilter)
export class CatsController {
@Get()
findAll() {
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}
}
Output
Custom Exception FiltersApproach 3: Global Exception Filters
Global exception filters may be used to deal with exceptions throughout the entire software. You can installation a global exception filter by using the usage of the app.UseGlobalFilters() method.
Example:
JavaScript
// custom-exception.filter.ts
import { HttpException, ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
@Catch(HttpException)
export class GlobalExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = exception.getStatus();
response.status(status).json({
statusCode: status,
message: exception.message,
timestamp: new Date().toISOString(),
});
}
}
JavaScript
//main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { GlobalExceptionFilter } from './global-exception.filter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new GlobalExceptionFilter());
await app.listen(3000);
}
bootstrap();
Output:
Global Exception FiltersApproach 4: HttpException
HttpException is a integrated magnificence in NestJS for throwing HTTP-related errors.
Syntax:
throw new HttpException('Custom error message', HttpStatus.FORBIDDEN);
Example:
JavaScript
//.\src\example\example.controller.ts
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
@Controller('example')
export class ExampleController {
@Get()
findAll() {
throw new HttpException(
{
statusCode: HttpStatus.FORBIDDEN,
message: 'Forbidden resource',
},
HttpStatus.FORBIDDEN,
);
}
}
Output:
{
"statusCode": 403,
"message": "Forbidden resource"
}
Approach 5: Using Middleware for Error Handling
Middleware in NestJS also can be used for errors handling with the aid of catching exceptions and modifying the reaction.
Example:
JavaScript
//.\src\example.controller.ts
import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';
@Controller('example')
export class ExampleController {
@Get()
findAll() {
throw new HttpException(
{
statusCode: HttpStatus.FORBIDDEN,
message: 'Forbidden resource',
},
HttpStatus.FORBIDDEN,
);
}
}
JavaScript
//.\src\app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ExampleController } from './example.controller';
import { ErrorHandlingMiddleware } from './error-handling.middleware';
@Module({
imports: [],
controllers: [AppController, ExampleController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(ErrorHandlingMiddleware)
.forRoutes('*');
}
}
Output
Using Middleware for Error HandlingApproach 6: Using Interceptors
Interceptors can trap mistakes and alter responses earlier than they may be despatched to the patron.
Example:
JavaScript
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ErrorInterceptor } from './error.interceptor';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new ErrorInterceptor());
await app.listen(3000);
}
bootstrap();
JavaScript
//error.interseptor.ts
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
catchError((error) => {
if (error instanceof HttpException) {
return throwError(() =>
new HttpException({ message: 'Error intercepted' }, error.getStatus()));
}
return throwError(() =>
new HttpException({ message: 'Error intercepted' }, 500));
}),
);
}
}
Output:
Using Interceptors
Similar Reads
Error Handling in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
7 min read
How to Handle Errors in Node.js ?
Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior
4 min read
How to Handle Syntax Errors in Node.js ?
If there is a syntax error while working with Node.js it occurs when the code you have written violates the rules of the programming language you are using. In the case of Node.js, a syntax error might occur if you have mistyped a keyword, or if you have forgotten to close a parenthesis or curly bra
4 min read
Guards in NestJS
NestJS is an extensible framework for building server-side applications using TypeScript. One of its key features is the ability to implement guards, which provide a way to intercept and control the flow of incoming requests to routes. Guards are used to implement authorization logic, ensuring that
2 min read
Controllers in NestJS
NestJS is a Node.js framework for building efficient, reliable, and scalable server-side applications. One of its core concepts is the use of controllers. Controllers in NestJS are responsible for handling incoming requests, processing them, and returning responses to the client. In this article, we
4 min read
Dependency Injection in NestJS
Dependency Injection (DI) is a fundamental concept in modern software development, enabling developers to create modular, maintainable, and testable code. NestJS, a progressive Node.js framework, uses DI to manage the dependencies of various components in an application. In this article, we'll explo
2 min read
Exception Filters in NestJS: Handling exceptions Gracefully.
NestJS comes with a built-in exceptions layer that handles all unhandled exceptions across the application. This layer ensures that when an exception is not handled by your application code, it is caught and processed, automatically sending a user-friendly response. In this article, weâll explore th
5 min read
Node.js new Error() Method
For generating and handling errors, Node.js supports so many mechanisms that occur during the running application and it is an inbuilt application, so we don't import any libraries. All the system errors that are raised by Node.js are inherited from the JavaScript's <Error> class and provide t
3 min read
NestJS Enable Cors In Production
Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to restrict web pages from making requests to domains other than the one from which they were originally served. While CORS is critical for preventing unauthorized data access, it often needs to be configured properly
5 min read
Error Classes in Node.js
Node.js inherits the JavaScript and system errors from the JavaScript <Error> class and it guarantees to provide the properties which are available on that class. The JavaScript exceptions that immediately throws errors using the throw mechanism that are handled by try...catch construct that i
4 min read