Performance: Built-in HTTP exceptions
This affects server response time and client perceived latency by how quickly errors are handled and sent back.
throw new NotFoundException('User not found');throw new Error('User not found');| Pattern | Server Processing | Error Handling Overhead | Response Time | Verdict |
|---|---|---|---|---|
| Generic Error Throw | Normal | High (extra conversion) | Slower | [X] Bad |
| Built-in HTTP Exception | Normal | Low (direct response) | Faster | [OK] Good |
NotFoundException in a NestJS controller?NotFoundExceptionBadRequestException in a NestJS controller method?throw new ExceptionClass() syntax.BadRequestExceptionthrow new BadRequestException('message').throw new [OK]async getUser(id: string) {
if (!id) {
throw new BadRequestException('ID is required');
}
const user = await this.userService.findById(id);
if (!user) {
throw new NotFoundException('User not found');
}
return user;
}id is missing, it throws BadRequestException (HTTP 400). If user is not found, it throws NotFoundException (HTTP 404).ForbiddenException:if (!user.isAdmin) {
ForbiddenException('Access denied');
}throw keyword followed by new ExceptionClass().ForbiddenException('Access denied') without throw and new, so it does nothing.ForbiddenException to add a custom error code in the response body?super() in the exception constructor customizes the JSON response.ForbiddenExceptionsuper(), correctly customizing the response.Pass the test and this pattern moves unknown