在这个例子中,当以这种方式实例化 HttpException 类时,会在端点中抛出一个未定义状态的异常,并变为状态 201(我相信在这种情况下就是这个状态,因为它是 POST 的默认状态)回应
NestJS版本:
"@nestjs/common": "^8.0.4"
@ApiTags('Test')
@Controller('test')
export class TestController {
@Post('')
async test() {
try {
const response = await this.testService.test();
console.log('response');
console.log({ response });
} catch (err) {
console.log('err');
console.log({ err });
}
}
}
@Injectable()
export class TestService {
async test() {
try {
throw new BadRequestException('Test Error');
} catch (error) {
throw new HttpException(error, undefined);
}
}
}
控制台日志和摩根日志:
err
{
err: HttpException: Test Error
at (...stack) {
response: [Object],
status: 400
},
status: undefined
}
}
POST /test 201 6.607 ms - -
这种行为正确吗?在我看来,以成功状态返回异常是极其危险的。默认情况下,当 HttpException 参数中未定义状态时,返回状态 500 不是更好吗?
我试图抛出异常,但惊讶地发现错误可以作为成功返回
@Post()
的默认状态是201
,所以是的,这是预期的。
但那是因为你正在处理异常而不是让nestjs来处理它。如果您从控制器中删除 try-catch,响应将是
500 Internal Server Error
(默认情况下)