Built-in HTTP exceptions help you send clear error messages to users when something goes wrong in your app. They make error handling simple and consistent.
When a user tries to access a resource that does not exist.
When a user sends invalid data to your API.
When a user is not authorized to perform an action.
When the server encounters an unexpected error.
When you want to inform the client about request limits or forbidden actions.
Syntax
NestJS
throw new HttpException('Error message', HttpStatus.STATUS_CODE);
You can use specific exceptions like NotFoundException or BadRequestException instead of HttpException for common cases.
HttpStatus.STATUS_CODE is a number like 404 for Not Found or 400 for Bad Request.
Examples
This sends a 404 error with a message 'User not found'.
NestJS
throw new NotFoundException('User not found');
This sends a 400 error when the user sends wrong data.
NestJS
throw new BadRequestException('Invalid input data');
This sends a 403 error with a custom message.
NestJS
throw new HttpException('Forbidden access', HttpStatus.FORBIDDEN);
Sample Program
This controller has a route to get a user by ID. If the user is not found, it throws a built-in NotFoundException. This sends a 404 error with a clear message to the client.
NestJS
import { Controller, Get, Param, NotFoundException } from'@nestjs/common';
@Controller('users')
export class UsersController {
private users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
@Get(':id')
getUser(@Param('id') id: string) {
const user = this.users.find(u => u.id === Number(id));
if (!user) {
throw new NotFoundException(`User with id ${id} not found`);
}
return user;
}
}
OutputSuccess
Important Notes
Use built-in exceptions to keep your API responses consistent and easy to understand.
You can create custom exceptions by extending HttpException if you need special behavior.
Summary
Built-in HTTP exceptions help handle errors clearly and simply.
Use specific exceptions like NotFoundException for common HTTP errors.
Throw exceptions to send proper HTTP status codes and messages to clients.
Practice
(1/5)
1. What is the purpose of using built-in HTTP exceptions like NotFoundException in a NestJS controller?
easy
A. To automatically log all requests to the server
B. To create new API routes dynamically
C. To improve database query performance
D. To send a clear HTTP error response with the correct status code and message
Solution
Step 1: Understand the role of HTTP exceptions in NestJS
Built-in HTTP exceptions are used to send error responses with specific HTTP status codes and messages.
Step 2: Identify the purpose of NotFoundException
This exception sends a 404 status code with a message indicating the resource was not found.
Final Answer:
To send a clear HTTP error response with the correct status code and message -> Option D
Quick Check:
HTTP exceptions = clear error responses [OK]
Hint: Exceptions send proper HTTP status codes and messages [OK]
Common Mistakes:
Thinking exceptions log requests automatically
Confusing exceptions with database operations
Assuming exceptions create routes
2. Which of the following is the correct way to throw a BadRequestException in a NestJS controller method?
easy
A. throw new BadRequestException('Invalid input');
B. return BadRequestException('Invalid input');
C. throw BadRequestException('Invalid input');
D. BadRequestException.throw('Invalid input');
Solution
Step 1: Recall the syntax for throwing exceptions in NestJS
Exceptions are thrown using the JavaScript throw new ExceptionClass() syntax.
Step 2: Check the correct usage for BadRequestException
The correct syntax is throw new BadRequestException('message').
Final Answer:
throw new BadRequestException('Invalid input'); -> Option A
Quick Check:
Throw exceptions with throw new [OK]
Hint: Use 'throw new ExceptionName()' to raise exceptions [OK]
Common Mistakes:
Omitting 'new' keyword when throwing exceptions
Using return instead of throw
Calling exception as a function without 'new'
3. Given this NestJS controller method, what HTTP status code will the client receive?
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;
}
medium
A. 200 if user found, 400 if ID missing, 404 if user not found
B. 200 always
C. 500 if user not found
D. 400 if user not found
Solution
Step 1: Analyze the conditions for exceptions
If id is missing, it throws BadRequestException (HTTP 400). If user is not found, it throws NotFoundException (HTTP 404).
Step 2: Understand the normal return
If no exceptions are thrown, the method returns the user with HTTP 200 status.
Final Answer:
200 if user found, 400 if ID missing, 404 if user not found -> Option A
Quick Check:
Exceptions map to HTTP codes 400 and 404, else 200 [OK]
Hint: Check exception types to know HTTP status codes sent [OK]
Common Mistakes:
Assuming 500 error instead of 404 for not found
Ignoring the BadRequestException case
Thinking exceptions return 200 status
4. Identify the error in this NestJS controller snippet that tries to throw a ForbiddenException:
if (!user.isAdmin) {
ForbiddenException('Access denied');
}
medium
A. Exception class name is incorrect
B. Missing 'throw' keyword before the exception
C. Exception message should be an object, not a string
D. ForbiddenException cannot be used in controllers
Solution
Step 1: Check how exceptions are thrown in NestJS
Exceptions must be thrown using the throw keyword followed by new ExceptionClass().
Step 2: Identify the missing part in the code
The code calls ForbiddenException('Access denied') without throw and new, so it does nothing.
Final Answer:
Missing 'throw' keyword before the exception -> Option B
Quick Check:
Always use 'throw new Exception()' to raise errors [OK]
Hint: Always use 'throw new' to raise exceptions [OK]
Common Mistakes:
Calling exception as a function without throw
Forgetting the 'new' keyword
Using wrong exception class names
5. You want to create a custom error response with status 403 and a detailed message using NestJS built-in exceptions. Which approach correctly extends ForbiddenException to add a custom error code in the response body?
hard
A. class CustomForbiddenException extends ForbiddenException {
constructor() {
super('Access denied');
this.errorCode = 123;
}
}
B. throw new ForbiddenException('Access denied', 123);
C. class CustomForbiddenException extends ForbiddenException {
constructor() {
super({ message: 'Access denied', errorCode: 123 });
}
}
D. throw new ForbiddenException({ message: 'Access denied' }, 123);
Solution
Step 1: Understand how to customize exception response body
Passing an object to super() in the exception constructor customizes the JSON response.
Step 2: Check which option correctly extends ForbiddenException
class CustomForbiddenException extends ForbiddenException {
constructor() {
super({ message: 'Access denied', errorCode: 123 });
}
} passes an object with message and errorCode to super(), correctly customizing the response.
Step 3: Identify why other options are incorrect
throw new ForbiddenException('Access denied', 123); incorrectly passes a second argument as number; class CustomForbiddenException extends ForbiddenException {
constructor() {
super('Access denied');
this.errorCode = 123;
}
} sets a property but does not affect response body; throw new ForbiddenException({ message: 'Access denied' }, 123); passes wrong parameters.
Final Answer:
class CustomForbiddenException extends ForbiddenException {
constructor() {
super({ message: 'Access denied', errorCode: 123 });
}
} -> Option C
Quick Check:
Pass object to super() to customize exception response [OK]
Hint: Pass an object with details to super() in custom exception [OK]
Common Mistakes:
Passing multiple arguments instead of one object
Setting properties without calling super() properly
Misunderstanding how to customize exception response
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.