[英]Nest.js sending custom response to client from an Exception
我正面临一个我想解决的问题......
我正在使用 Nest.js 作为 API 的后端框架和 Nuxt.js 用于客户端的项目......一切正常,但是当我试图在服务中抛出错误时,它被注入到 controller,我无法向客户端发送自定义响应。 我遇到的那些场景:
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,
});
}
}
似乎问题本身不是服务器,而是来自客户端。 登录错误不会记录object ,您需要记录错误。响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.