How to use the Nest.js exception filter for error handling
Unhandled exceptions can cause confusion and frustration for users. However, you can solve this problem with exception filters.
Nest.js exception filters provide a way to catch and handle exceptions globally or on a per-controller basis. They allow you to focus on error handling logic, format error responses, and provide consistent error handling across the application. Let's learn about exception filters and how to use them for proper application error handling.
Default error handling in Nest.js
By default, Nest.js has an exception class, which handles any exceptions that the application code cannot handle.
When unresolved errors occur in the application, Nest.js will detect them and return a 100 Internet Server error to the client. The JSON that Nest.js returns in this case looks like this:
{ "statusCode": 500, "message": "Internal server error" }
If the error object generated by code contains statusCode and message , Nest.js will return these values instead of the default response.
To avoid the common behavior of sending a more detailed error response to the client, you need to diligently handle all possible errors in the application. You can achieve this using Nest.js's built-in or custom exception filters.
Create a custom exception filter
This example will try to create a filter that handles all HTTP exceptions. Start with a file named http.exception.ts and add the following imports to it:
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, } from '@nestjs/common'; import { Request, Response } from 'express';
These imports serve the following purposes:
- ExceptionFilter : an interface that describes an exception filter implementation.
- Catch : A decorator that marks the class as a Nest exception filter.
- ArgumentsHost : This interface provides methods for retrieving arguments passed to a handler. It allows you to select the appropriate execution body (for example, HTTP, RPC, or WebSockets) to retrieve arguments.
- HttpException : This is a class that defines basic HTTP Nest exceptions.
- Request & Response : They are the interfaces for an Express.js query and the corresponding response object.
Next, create a class, HttpExceptionFilter , that implements ExceptionFilter . Annotate it with the Catch decorator to indicate that it handles HttpExceptions:
@Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter {}
Next, fill the class with this code:
catch(exception: HttpException, host: ArgumentsHost) { // Lấy đối tượng phản hồi từ máy chủ đối số const ctx = host.switchToHttp(); const response = ctx.getResponse(); // Lấy đối tượng phản hồi từ máy chủ đối số const request = ctx.getRequest(); // Lấy code trạng thái từ ngoại lệ const status = exception.getStatus(); // Gửi phản hồi JSON bằng đối tượng phản hồi response.status(status).json({ statusCode: status, timestamp: new Date().toISOString(), path: request.url, message: exception.message || exception.getResponse()['message'] || 'Internal Server Error', }); }
This block of code retrieves the query and response objects from the ArgumentsHost object and retrieves related information from this exception. It returns a JSON object response, with error details, to the client.
Link exception filters
You can associate an exception filter with a driver or the entire application, as needed.
To bind a global exception filter, first import the exception filter into the main.ts file . Then pass the instance of the exception filter into the app.useGlobalFilters method :
// main.ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { HttpExceptionFilter } from './exception/http.exception'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Liên kết bộ lọc với ứng dụng app.useGlobalFilters(new HttpExceptionFilter()); await app.listen(4050); } bootstrap();
To bind an exception to a controller, enter the UseFilters decorator and your exception filter. Annotate the controller class with the @UseFilters decorator and pass the instance of the exception filter as an argument to the decorator:
@Controller() @UseFilters(new HttpExceptionFilter()) export class AppController {}
Where you bind the filter determines the scope of error handling. Controller binding filters will only serve the controller you're binding to, app binding filters will serve the entire app.
Above is how to use Nest.js's exception filter to handle errors . Hope the article is useful to you.
You should read it
- How to Containerize a Nest.js Application Using Docker and Docker Compose
- How to use Google Nest to find phones
- Review Google Nest Wifi: Mesh router is smarter
- Natural marvels, ant herds of millions connect the tail of a living bridge to break the bee's nest
- How to Nest an Image Inside Another Image in Photoshop
- The most unique and beautiful nest eggs in the world of insects
- Xiaomi security cameras show pictures of strangers' homes, Google immediately disables these devices
- Tips and tricks that JavaScript programmers need to know
- Beginners of computer programming need to focus on what?
- Udemy's top 5 JavaScript courses
- What is JavaScript?
- 30 hornets massacred 30,000 bees in 3 hours
Maybe you are interested
The 12th and 13th generation Core CPUs were so good that AMD almost lost the PC market to Intel What's the difference between Intel Core and Intel Core X CPUs? Intel is back with foldable laptops Panasonic refreshed the Toughbook 31 series with Broadwell chips Toshiba Vietnam launches notebook collection for summer 2011 Lenovo launches a laptop duo using Sandy Bridge chip