Careeroza
Built-in HTTP Exceptions
Throw and NestJS Answers
Throw an exception anywhere (controller, service, guard, pipe). The built-in global filter turns it into a JSON response. Unknown errors become 500.
| Exception | Status |
|---|---|
BadRequestException | 400 |
UnauthorizedException | 401 |
ForbiddenException | 403 |
NotFoundException | 404 |
ConflictException | 409 |
UnprocessableEntityException | 422 |
InternalServerErrorException | 500 |
ServiceUnavailableException | 503 |
import { ConflictException, HttpException, HttpStatus, NotFoundException } from '@nestjs/common';
export class Examples {
run(id: number, email: string) {
throw new NotFoundException(`Product ${id} not found`);
throw new ConflictException({ code: 'EMAIL_TAKEN', message: `${email} is already registered` });
throw new HttpException('Payment required', HttpStatus.PAYMENT_REQUIRED);
throw new NotFoundException('Order not found', { cause: new Error('db miss'), description: 'Order lookup' });
}
}Default Responses
Example
curl http://localhost:3000/products/999
curl -X POST http://localhost:3000/auth/register -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"Secret123"}'
curl http://localhost:3000/crashExample output
{"message":"Product 999 not found","error":"Not Found","statusCode":404}
{"code":"EMAIL_TAKEN","message":"[email protected] is already registered"}
{"statusCode":500,"message":"Internal server error"}Note: When you pass an object to an exception, that object becomes the whole response body. The real error of a 500 is logged on the server but hidden from the client.