简体   繁体   中英

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. Those the scenarios that i've faced:

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

This returns me this error in the client, if the user already exists but it doesn't send the json to the client.

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. 在此处输入图像描述 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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