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

如何在nestjs中从DTO返回一个对象作为错误消息?

2 个月前提问
2 个月前修改
浏览次数38

1个答案

1

在使用NestJS时,如果需要在发生错误时从DTO(数据传输对象)返回一个具体的错误对象,我们可以通过几种方式来实现这一目标。这里,我将介绍如何通过异常过滤器(exception filters)和拦截器(interceptors)来完成这个需求。

使用异常过滤器 (Exception Filters)

异常过滤器是处理和转换异常输出的理想选择。我们可以创建一个自定义的异常过滤器来捕捉特定的异常,并从DTO中返回错误信息。

步骤 1: 定义 DTO

首先,我们需要定义一个错误消息DTO,这个DTO将定义错误消息的结构。

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

步骤 2: 创建异常过滤器

然后,我们可以创建一个异常过滤器来捕获异常并返回定义好的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, // 这里根据实际情况可能需要调整 error: (exceptionResponse as any).error, // 这里根据实际情况可能需要调整 }; response .status(status) .json(errorResponse); } }

步骤 3: 使用过滤器

最后,在你的NestJS模块或者控制器中使用这个异常过滤器。

typescript
// app.module.ts 或者任何特定的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: '这里是错误信息', error: 'BadRequest', }, 400); } }

通过这种方式,我们就可以在抛出异常时,利用DTO来格式化返回的错误信息。这种方法可以帮助我们保持错误消息的一致性,并且便于维护和测试。

2024年7月24日 10:03 回复

你的答案