Custom exception classes help you create clear and specific error messages in your NestJS app. They make your code easier to understand and fix.
Custom exception classes in NestJS
import { HttpException, HttpStatus } from '@nestjs/common'; export class CustomException extends HttpException { constructor(message: string) { super(message, HttpStatus.BAD_REQUEST); } }
Extend HttpException to create your own error class.
Use super(message, statusCode) to set the error message and HTTP status.
import { HttpException, HttpStatus } from '@nestjs/common'; export class NotFoundException extends HttpException { constructor() { super('Resource not found', HttpStatus.NOT_FOUND); } }
import { HttpException, HttpStatus } from '@nestjs/common'; export class ValidationException extends HttpException { constructor(errors: string[]) { super({ message: 'Validation failed', errors }, HttpStatus.BAD_REQUEST); } }
This example shows a custom exception class and a filter that catches it. When you visit the '/error' route, it throws the custom error and returns a JSON response with status 403 and the message.
import { Controller, Get, UseFilters } from '@nestjs/common'; import { HttpException, HttpStatus, ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common'; // Custom exception class export class MyCustomException extends HttpException { constructor() { super('This is a custom error', HttpStatus.FORBIDDEN); } } // Exception filter to catch custom exception @Catch(MyCustomException) export class MyCustomExceptionFilter implements ExceptionFilter { catch(exception: MyCustomException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); response.status(exception.getStatus()).json({ statusCode: exception.getStatus(), message: exception.message }); } } @Controller() @UseFilters(MyCustomExceptionFilter) export class AppController { @Get('error') throwError() { throw new MyCustomException(); } }
Always extend HttpException for HTTP errors in NestJS.
Use exception filters to customize how errors are sent to clients.
Custom exceptions improve code clarity and API responses.
Custom exception classes let you create specific error messages.
They extend HttpException and set message and status.
Use filters to handle and format these exceptions in your app.
Practice
Solution
Step 1: Understand the role of custom exceptions
Custom exceptions in NestJS help you send clear, specific error messages with HTTP status codes.Step 2: Compare with other options
Options B, C, and D describe unrelated features not handled by custom exceptions.Final Answer:
To define specific error messages and HTTP status codes for your app -> Option DQuick Check:
Custom exceptions = specific messages + status [OK]
- Thinking custom exceptions replace JavaScript Error globally
- Assuming they log errors automatically
- Confusing exceptions with HTTP methods
Solution
Step 1: Check syntax for custom exception
In NestJS, custom exceptions extend HttpException and call super with message and status.Step 2: Validate options
class MyException extends HttpException { constructor() { super('Error', 400); } } correctly extends HttpException and calls super with message and status code. Others do not follow NestJS pattern.Final Answer:
class MyException extends HttpException { constructor() { super('Error', 400); } } -> Option BQuick Check:
Extend HttpException + super(message, status) [OK]
- Not extending HttpException
- Not calling super() with message and status
- Using plain functions instead of classes
class ForbiddenException extends HttpException {
constructor() {
super('Access denied', 403);
}
}Solution
Step 1: Read the constructor call
The constructor calls super with message 'Access denied' and status 403.Step 2: Understand HttpException behavior
The second argument to super is the HTTP status code returned when exception is thrown.Final Answer:
403 -> Option CQuick Check:
Status code = 403 from super() call [OK]
- Confusing message with status code
- Assuming default 500 status
- Ignoring the status argument in super()
class BadRequestException extends HttpException {
constructor() {
super('Bad request');
}
}Solution
Step 1: Check super() arguments
The super() call only has a message string, but HttpException requires message and status code.Step 2: Understand HttpException constructor
HttpException constructor needs both message and HTTP status code to work correctly.Final Answer:
Missing HTTP status code in super() call -> Option AQuick Check:
super() needs message + status [OK]
- Forgetting the status code argument
- Thinking message alone is enough
- Misunderstanding HttpException constructor
class CustomErrorException extends HttpException {
constructor() {
super(
{ errorCode: 1234, message: 'Custom error' },
400
);
}
}Solution
Step 1: Review HttpException constructor usage
HttpException accepts either a string or an object as the first argument for the response body.Step 2: Confirm JSON response with status code
Passing an object with errorCode and message as first argument and 400 as second is valid and sends JSON response with status 400.Final Answer:
This code correctly sends a JSON object with errorCode and message and HTTP 400 status -> Option AQuick Check:
HttpException supports object response + status [OK]
- Thinking only strings allowed in super()
- Putting status code inside JSON object
- Believing custom exceptions can't send JSON
Ready to prove it?
Pass the test and this pattern moves unknown
