我正面临要解决的问题...
我正在使用Nest.js作为API的后端框架,使用Nuxt.js作为Client的程序...一切工作正常,但是当我尝试在服务中引发错误时,该错误被注入到控制器中,因此我无法向客户端发送自定义响应。我遇到过的那些场景:
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,
});
}
}
似乎问题本身不是服务器,而是客户端。登录errors不会记录该对象,您需要登录errors.response