How to use the Nest.js exception filter for error handling
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
- 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
May be interested
- Handling copy - HANDLING DUPLICATE in SQLthis article will show you in detail how to handle copy - handling duplicate with specific examples to make it easier to visualize and capture.
- Error and Exception in Pythonpython often produces exceptions when an error occurs during execution. quantum will work with you to learn about the different exceptions built into this language.
- How to fix Blue Machine Check Exception screen error on Windows 10machine check exception blue screen error is a serious windows system error. this article will show you some ways to fix this error.
- How to fix Unhandled Exception Has Occurred errors on Windows 10the unhandled exception exception has nothing to do with a specific application making it more difficult to resolve. this article will guide you some ways to fix unhandled exception has occurred on windows 10.
- Photoshop CS: Eclipse effectin the previous article, i showed you how to create a color swirl using a few effects from the filter filter. there will be many more interesting things from this filter filter that make sure
- Fix Error 0x0000001E: KMODE EXCEPTION NOT HANDLED On Windowsyou often get the error message '0x0000001e: kmode exception not handled' so where is the error and how to fix it. let's find out through the following article
- Steps to fix 'System Thread Exception Not Handled' errorthere are many causes of 'system thread exception not handled' error on windows 10 and there is no specific cause.
- What is a filter? How to use Filter in photography?in photography, filter means glass filters used in many different situations, such as taking photos of low-light natural conditions, or enhancing colors, ...
- How to fix 'Filter Failed' printer error on Macif your printer gives you a filter failed error when you send a print job from your mac, you're not alone. this issue affects printers from epson, canon, hp, and many other brands.
- What is a UF filter? Compare UF, RO and Nano water filtration technologiesthe article of tipsmake.com will help you understand what uf filter is and what uf water filtration technology has advantages and disadvantages compared to ro and nano.