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.

ExceptionStatus
BadRequestException400
UnauthorizedException401
ForbiddenException403
NotFoundException404
ConflictException409
UnprocessableEntityException422
InternalServerErrorException500
ServiceUnavailableException503
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/crash

Example 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.