乐闻世界logo
搜索文章和话题

How to return an object as error message from DTO in nestjs?

1个答案

1

When using NestJS, if you need to return a specific error object from a DTO when an error occurs, you can achieve this in several ways. Here, I will explain how to achieve this using exception filters and interceptors.

Using Exception Filters (Exception Filters)

Exception filters are an ideal choice for handling and transforming exception outputs. We can create a custom exception filter to catch specific exceptions and return the error object from the DTO.

Step 1: Define DTO

First, we need to define an error message DTO that defines the structure of the error response.

typescript
// error-response.dto.ts export class ErrorResponseDto { statusCode: number; message: string; error: string; }

Step 2: Create Exception Filter

Then, we can create an exception filter to catch exceptions and return the defined DTO.

typescript
// http-exception.filter.ts import { ExceptionFilter, Catch, HttpException, ArgumentsHost } from '@nestjs/common'; import { Response } from 'express'; import { ErrorResponseDto } from './error-response.dto'; @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse<Response>(); const status = exception.getStatus(); const exceptionResponse = exception.getResponse(); const errorResponse: ErrorResponseDto = { statusCode: status, message: (exceptionResponse as any).message, // Adjust based on actual implementation error: (exceptionResponse as any).error, // Adjust based on actual implementation }; response .status(status) .json(errorResponse); } }

Step 3: Use the Filter

Finally, apply this exception filter in your NestJS module or controller.

typescript
// app.module.ts or any specific controller.ts import { Module, Controller, Get, UseFilters } from '@nestjs/common'; import { AppService } from './app.service'; import { HttpExceptionFilter } from './http-exception.filter'; @Controller() @UseFilters(new HttpExceptionFilter()) export class AppController { constructor(private readonly appService: AppService) {} @Get() getHello(): string { throw new HttpException({ message: 'Here is the error message', error: 'BadRequest', }, 400); } }

By doing this, you can format the error response when throwing exceptions using the DTO. This approach helps maintain consistency in error messages and makes maintenance and testing easier.

2024年7月24日 10:03 回复

你的答案