简体   繁体   English

Nest.js 从异常向客户端发送自定义响应

[英]Nest.js sending custom response to client from an Exception

I'm facing a problem that i'd like to fix...我正面临一个我想解决的问题......

I'm working on a procject using Nest.js as Backend framework for APIs, and Nuxt.js for Client... Everything is working fine, but when i'm trying to throw an error in a service, that is injected into the controller, i'm not able to send a custom response to the client.我正在使用 Nest.js 作为 API 的后端框架和 Nuxt.js 用于客户端的项目......一切正常,但是当我试图在服务中抛出错误时,它被注入到 controller,我无法向客户端发送自定义响应。 Those the scenarios that i've faced:我遇到的那些场景:

account.service.ts 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 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)
    }
}

This returns me this error in the client, if the user already exists but it doesn't send the json to the client.如果用户已经存在但它没有将 json 发送到客户端,这将在客户端返回此错误。

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

If i change it res.json(e), it sends me to the client the error with status 201 as you can see in the image, but the response is fine in all scenarios.如果我更改它 res.json(e),它会向客户端发送状态为 201 的错误,如图所示,但在所有情况下响应都很好。 在此处输入图像描述 So the question is... how i can get this response with correct status code?所以问题是......我怎样才能用正确的状态码得到这个响应?

This is the Exception Filter:这是异常过滤器:

 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,
                });
        }
    }

Seems that the problem itself wasn't the server, but from client.似乎问题本身不是服务器,而是来自客户端。 Loggin the errors doesnt log the object, you need to log errors.response登录错误不会记录object ,您需要记录错误。响应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM