Discover how a simple throw can replace messy error checks and make your server smarter!
Why Built-in HTTP exceptions in NestJS? - Purpose & Use Cases
Imagine writing a web server where you must manually check every error and write custom code to send the right HTTP status and message for each problem.
This manual error handling is slow, repetitive, and easy to get wrong. You might forget to send the correct status code or message, confusing users and making debugging harder.
Built-in HTTP exceptions in NestJS provide ready-made error classes that automatically send the right HTTP status and message, making error handling clean and consistent.
if (!user) { res.status(404).send('User not found'); }
throw new NotFoundException('User not found');This lets you focus on your app logic while NestJS handles clear, standard error responses for you.
When a user tries to access a missing page, NestJS's built-in exceptions quickly send a 404 error with a helpful message without extra code.
Manual error handling is repetitive and error-prone.
Built-in HTTP exceptions simplify and standardize error responses.
They improve code clarity and user experience.
Practice
NotFoundException in a NestJS controller?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
This exception sends a 404 status code with a message indicating the resource was not found.NotFoundExceptionFinal Answer:
To send a clear HTTP error response with the correct status code and message -> Option DQuick Check:
HTTP exceptions = clear error responses [OK]
- Thinking exceptions log requests automatically
- Confusing exceptions with database operations
- Assuming exceptions create routes
BadRequestException in a NestJS controller method?Solution
Step 1: Recall the syntax for throwing exceptions in NestJS
Exceptions are thrown using the JavaScriptthrow new ExceptionClass()syntax.Step 2: Check the correct usage for
The correct syntax isBadRequestExceptionthrow new BadRequestException('message').Final Answer:
throw new BadRequestException('Invalid input'); -> Option AQuick Check:
Throw exceptions withthrow new[OK]
- Omitting 'new' keyword when throwing exceptions
- Using return instead of throw
- Calling exception as a function without 'new'
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;
}Solution
Step 1: Analyze the conditions for exceptions
Ifidis missing, it throwsBadRequestException(HTTP 400). If user is not found, it throwsNotFoundException(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 AQuick Check:
Exceptions map to HTTP codes 400 and 404, else 200 [OK]
- Assuming 500 error instead of 404 for not found
- Ignoring the BadRequestException case
- Thinking exceptions return 200 status
ForbiddenException:if (!user.isAdmin) {
ForbiddenException('Access denied');
}Solution
Step 1: Check how exceptions are thrown in NestJS
Exceptions must be thrown using thethrowkeyword followed bynew ExceptionClass().Step 2: Identify the missing part in the code
The code callsForbiddenException('Access denied')withoutthrowandnew, so it does nothing.Final Answer:
Missing 'throw' keyword before the exception -> Option BQuick Check:
Always use 'throw new Exception()' to raise errors [OK]
- Calling exception as a function without throw
- Forgetting the 'new' keyword
- Using wrong exception class names
ForbiddenException to add a custom error code in the response body?Solution
Step 1: Understand how to customize exception response body
Passing an object tosuper()in the exception constructor customizes the JSON response.Step 2: Check which option correctly extends
class CustomForbiddenException extends ForbiddenException { constructor() { super({ message: 'Access denied', errorCode: 123 }); } } passes an object with message and errorCode toForbiddenExceptionsuper(), 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 CQuick Check:
Pass object to super() to customize exception response [OK]
- Passing multiple arguments instead of one object
- Setting properties without calling super() properly
- Misunderstanding how to customize exception response
Ready to prove it?
Pass the test and this pattern moves unknown
