当状态未定义时,NestJS HttpException 类返回状态 201

问题描述 投票:0回答:1

在这个例子中,当以这种方式实例化 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 不是更好吗?

我试图抛出异常,但惊讶地发现错误可以作为成功返回

javascript node.js express http nestjs
1个回答
0
投票

@Post()
的默认状态是
201
,所以是的,这是预期的。

但那是因为你正在处理异常而不是让nestjs来处理它。如果您从控制器中删除 try-catch,响应将是

500 Internal Server Error
(默认情况下)

© www.soinside.com 2019 - 2024. All rights reserved.