【问题标题】:Nest.js sending custom response to client from an ExceptionNest.js 从异常向客户端发送自定义响应
【发布时间】:2020-08-17 00:48:44
【问题描述】:

我遇到了一个我想解决的问题...

我正在使用 Nest.js 作为 API 的后端框架和 Nuxt.js 作为客户端的项目... 一切正常,但是当我试图在服务中抛出错误时,将其注入控制器,我无法向客户端发送自定义响应。我遇到的那些场景:

account.service.ts

 async createAccount(_account: AccountEntity){
    return await this.accountRepository.save(_account)
}

async _accountExists(_account: AccountEntity) {
    const itExists = await this.findOne(_account)
    if(itExists){
        throw new ConflictException(`Username already exists!`)
    }
}

account.controller.ts

@Post()
@UseFilters(new HttpExceptionFilter())
async createAccount(@Body() userAccount: createAccountDto, @Res() res: Response) {
    try {
        await this.accountService._accountExists(userAccount).then(async () => {
            return await this.accountService.createAccount(userAccount)
        })
    } catch (e) {
        res.status(e.status).json(e.message)
    }
}

如果用户已经存在但它没有将 json 发送到客户端,这将在客户端返回此错误。

POST http://localhost:3000/account 409 (Conflict)
Request failed with status code 409

如果我更改它 res.json(e),它会向客户端发送状态为 201 的错误,如图所示,但在所有情况下响应都很好。 所以问题是......我怎样才能用正确的状态码得到这个响应?

这是异常过滤器:

 import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
    import { Request, Response } from 'express';

    @Catch(HttpException)
    export class HttpExceptionFilter 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();

            response
                .status(status)
                .json({
                    statusCode: status,
                    name: exception.name,
                    message: exception.message.message,
                    timestamp: new Date().toISOString(),
                    path: request.url,
                });
        }
    }

【问题讨论】:

    标签: javascript express axios nuxt.js nestjs


    【解决方案1】:

    似乎问题本身不是服务器,而是来自客户端。 登录errors不记录对象,需要记录errors.response

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 2021-03-19
      • 2017-08-11
      • 2013-09-14
      相关资源
      最近更新 更多