Reputation: 23
In this example, when the HttpException class is instantiated in this way, an exception is thrown with undefined status and becomes status 201 (I believe that in this case it is this status as it is the default status of a POST) in the endpoint response
NestJS version:
"@nestjs/common": "^8.0.4"
@ApiTags('Test')
@Controller('test')
export class TestController {
@Post('')
async test() {
await this.testService.test();
}
}
@Injectable()
export class TestService {
async test() {
try {
throw new BadRequestException('Test Error');
} catch (error) {
throw new HttpException(error, undefined);
}
}
}
Console logs and morgans logs:
err
{
err: HttpException: Test Error
at (...stack) {
response: [Object],
status: 400
},
status: undefined
}
}
POST /test 201 6.607 ms - -
Is this behavior correct? In my opinion, it is extremely dangerous for an exception to be returned with a success status. By default, perhaps wouldn't it be better to return status 500 when it is not defined in the HttpException parameter?
I was trying to throw an exception and was surprised that an error could be returned as a success
Upvotes: 0
Views: 149
Reputation: 6685
the default status for @Post()
is 201
, so yes, that's expected.
But that's because you're handling the exception instead of letting nestjs to handle it. If you drop the try-catch from the controller, the response will be 500 Internal Server Error
(by default)
Upvotes: 0