Bird
Raised Fist0
NestJSframework~15 mins

Built-in HTTP exceptions in NestJS - Deep Dive

Choose your learning style10 modes available
Overview - Built-in HTTP exceptions
What is it?
Built-in HTTP exceptions in NestJS are pre-made error classes that represent common HTTP error responses. They help you send proper error messages and status codes to clients when something goes wrong. Instead of writing error handling from scratch, you use these ready-made exceptions to keep your code clean and consistent. They cover many standard HTTP errors like 404 Not Found or 400 Bad Request.
Why it matters
Without built-in HTTP exceptions, developers would have to manually create error responses and set status codes every time an error occurs. This can lead to inconsistent error handling and more bugs. Using these exceptions makes your API predictable and easier to maintain, improving the experience for both developers and users. It also speeds up development by providing a standard way to handle errors.
Where it fits
Before learning built-in HTTP exceptions, you should understand basic NestJS controllers and how HTTP requests and responses work. After mastering exceptions, you can explore custom exception filters and advanced error handling techniques to customize responses further.
Mental Model
Core Idea
Built-in HTTP exceptions are like ready-made error messages that automatically tell the client what went wrong using standard HTTP codes and messages.
Think of it like...
Imagine you have a set of pre-written apology letters for common mistakes at work. Instead of writing a new letter every time, you pick the right one and send it quickly and clearly. Built-in HTTP exceptions are like those apology letters for your web app.
┌───────────────────────────────┐
│ Client sends HTTP request     │
└──────────────┬────────────────┘
               │
               ▼
┌───────────────────────────────┐
│ NestJS Controller processes   │
│ request                       │
└──────────────┬────────────────┘
               │
               ▼
┌───────────────────────────────┐
│ Error occurs?                 │
│ ┌───────────────┐            │
│ │ Yes           │            │
│ └──────┬────────┘            │
│        ▼                     │
│ ┌─────────────────────────┐ │
│ │ Throw built-in HTTP     │ │
│ │ exception (e.g., 404)   │ │
│ └────────────┬────────────┘ │
│              │              │
│              ▼              │
│ ┌─────────────────────────┐ │
│ │ NestJS sends HTTP error │ │
│ │ response with code &    │ │
│ │ message                 │ │
│ └─────────────────────────┘ │
└───────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding HTTP status codes
🤔
Concept: Learn what HTTP status codes are and why they matter in web communication.
HTTP status codes are numbers sent by a server to tell the client what happened with their request. For example, 200 means success, 404 means the requested page was not found, and 500 means a server error happened. These codes help clients understand if their request worked or if there was a problem.
Result
You can recognize common HTTP status codes and their meanings.
Knowing HTTP status codes is essential because built-in exceptions use these codes to communicate errors clearly.
2
FoundationBasics of NestJS exception handling
🤔
Concept: Learn how NestJS handles errors using exceptions and how they affect HTTP responses.
In NestJS, when something goes wrong, you can throw an exception. NestJS catches these exceptions and converts them into HTTP responses with status codes and messages. This automatic handling means you don't have to manually set response codes every time an error happens.
Result
You understand that throwing exceptions in NestJS controls the HTTP response sent to clients.
Recognizing that exceptions control HTTP responses helps you write cleaner error handling code.
3
IntermediateUsing built-in HTTP exception classes
🤔Before reading on: do you think you must create your own error classes or can you use ready-made ones in NestJS? Commit to your answer.
Concept: NestJS provides built-in exception classes for common HTTP errors to simplify error handling.
NestJS has classes like NotFoundException, BadRequestException, UnauthorizedException, and more. You can throw these directly in your code. For example, throw new NotFoundException('User not found') sends a 404 status with that message. This saves time and ensures consistent error responses.
Result
You can throw standard HTTP errors easily with descriptive messages.
Understanding built-in exceptions lets you avoid reinventing error handling and keeps your API consistent.
4
IntermediateCustomizing built-in exception responses
🤔Before reading on: do you think built-in exceptions allow custom messages or are they fixed? Commit to your answer.
Concept: Built-in exceptions let you add custom messages and details to error responses.
When you create a built-in exception, you can pass a message or an object with extra info. For example, new BadRequestException({ error: 'Invalid input', code: 123 }) sends a JSON response with your details. This helps clients understand exactly what went wrong.
Result
Error responses include helpful, customized information for clients.
Knowing how to customize exceptions improves communication between your API and its users.
5
AdvancedHow NestJS maps exceptions to HTTP responses
🤔Before reading on: do you think NestJS uses a fixed map or dynamic logic to convert exceptions to HTTP responses? Commit to your answer.
Concept: NestJS uses an internal exception filter that converts thrown exceptions into HTTP responses automatically.
When you throw a built-in exception, NestJS's built-in exception filter catches it. It reads the status code and message from the exception object and sends an HTTP response accordingly. This filter can be overridden or extended for custom behavior.
Result
You understand the automatic flow from exception throw to HTTP response.
Understanding this mechanism helps you customize error handling and debug issues effectively.
6
ExpertExtending and combining built-in exceptions
🤔Before reading on: do you think you can create your own exceptions by extending built-in ones? Commit to your answer.
Concept: You can create custom exceptions by extending built-in HTTP exception classes to add specialized behavior.
By extending classes like HttpException or NotFoundException, you can create your own exceptions with extra properties or methods. This is useful for complex APIs needing specific error formats or logging. You can also throw multiple exceptions in sequence or wrap exceptions for layered error handling.
Result
You can build tailored error handling that fits complex real-world needs.
Knowing how to extend exceptions unlocks advanced error handling patterns used in professional applications.
Under the Hood
Built-in HTTP exceptions in NestJS are classes that extend a base HttpException class. When you throw one, NestJS's internal exception filter catches it during request processing. The filter reads the exception's status code and response message, then formats and sends an HTTP response to the client. This process uses JavaScript's class inheritance and NestJS's middleware pipeline to handle errors uniformly.
Why designed this way?
NestJS was designed to simplify error handling by providing reusable exception classes that map directly to HTTP status codes. This avoids repetitive code and enforces consistency. Alternatives like manual response handling were error-prone and verbose. The class-based approach fits well with TypeScript and object-oriented design, making it easy to extend and customize.
┌───────────────┐
│ Throw Exception│
│ (e.g., 404)   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ NestJS Exception│
│ Filter catches  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Reads status   │
│ code & message │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Sends HTTP    │
│ response with │
│ code & body   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think throwing a built-in exception always stops the request immediately? Commit to yes or no.
Common Belief:Throwing a built-in HTTP exception immediately stops all code execution and sends the response.
Tap to reveal reality
Reality:Throwing an exception interrupts the current function but other asynchronous operations may still run unless properly handled.
Why it matters:Assuming immediate stop can cause unexpected side effects or resource leaks if cleanup code is not managed.
Quick: Do you think built-in exceptions only send plain text messages? Commit to yes or no.
Common Belief:Built-in HTTP exceptions only send simple text messages as error responses.
Tap to reveal reality
Reality:They can send JSON objects or any serializable data as the response body, allowing rich error details.
Why it matters:Limiting error responses to text reduces the ability to communicate useful debugging info to clients.
Quick: Do you think you must always create custom exceptions for every error? Commit to yes or no.
Common Belief:You must create custom exceptions for all error cases to handle them properly.
Tap to reveal reality
Reality:Most common errors are covered by built-in exceptions, and custom exceptions should be used only when needed.
Why it matters:Overusing custom exceptions adds unnecessary complexity and reduces code clarity.
Quick: Do you think built-in exceptions automatically log errors? Commit to yes or no.
Common Belief:Built-in HTTP exceptions automatically log error details to the console or files.
Tap to reveal reality
Reality:They only format HTTP responses; logging must be implemented separately if needed.
Why it matters:Assuming automatic logging can cause missed error tracking and debugging difficulties.
Expert Zone
1
Built-in exceptions can be combined with custom exception filters to modify or enrich error responses globally.
2
Extending HttpException allows adding metadata or error codes that clients can use for better error handling.
3
Throwing exceptions inside asynchronous code requires careful handling to avoid unhandled promise rejections.
When NOT to use
Avoid using built-in HTTP exceptions for non-HTTP errors like internal logic errors or background tasks. Instead, use standard error handling or custom error classes. For APIs needing very custom error formats, consider custom exception filters or middleware.
Production Patterns
In production, developers use built-in exceptions for standard HTTP errors and combine them with global exception filters for logging, metrics, and consistent error formats. Custom exceptions extend built-in ones to add domain-specific error codes. This pattern keeps APIs robust, maintainable, and user-friendly.
Connections
Exception handling in programming languages
Built-in HTTP exceptions are a specialized form of general exception handling tailored for web responses.
Understanding general exception handling helps grasp how NestJS exceptions control program flow and error reporting.
REST API design principles
Built-in HTTP exceptions enforce standard HTTP status codes, which are core to RESTful API design.
Knowing REST principles clarifies why using correct HTTP status codes improves API clarity and client interaction.
Customer service escalation processes
Just like built-in exceptions escalate issues to clients with clear codes, customer service uses standard escalation levels to communicate problems.
Recognizing this parallel shows how structured communication improves problem resolution in both software and real life.
Common Pitfalls
#1Throwing generic Error instead of built-in HTTP exceptions
Wrong approach:throw new Error('User not found');
Correct approach:throw new NotFoundException('User not found');
Root cause:Misunderstanding that generic errors do not automatically set HTTP status codes, leading to 500 Internal Server Error responses instead of meaningful ones.
#2Not passing a message to the exception
Wrong approach:throw new BadRequestException();
Correct approach:throw new BadRequestException('Invalid user input');
Root cause:Omitting messages makes error responses less informative, confusing API clients.
#3Catching exceptions but not rethrowing or handling properly
Wrong approach:try { throw new NotFoundException(); } catch (e) { /* empty catch */ }
Correct approach:try { throw new NotFoundException(); } catch (e) { throw e; }
Root cause:Swallowing exceptions prevents NestJS from sending error responses, causing requests to hang or return success incorrectly.
Key Takeaways
Built-in HTTP exceptions in NestJS provide ready-made error classes that map to standard HTTP status codes and messages.
Using these exceptions ensures consistent, clear, and maintainable error handling in your web applications.
You can customize exception messages and extend built-in classes for advanced error handling needs.
NestJS automatically converts thrown exceptions into HTTP responses via an internal exception filter.
Avoid common mistakes like throwing generic errors or swallowing exceptions to ensure proper error communication.

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

  1. 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.
  2. Step 2: Identify the purpose of NotFoundException

    This exception sends a 404 status code with a message indicating the resource was not found.
  3. Final Answer:

    To send a clear HTTP error response with the correct status code and message -> Option D
  4. 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

  1. Step 1: Recall the syntax for throwing exceptions in NestJS

    Exceptions are thrown using the JavaScript throw new ExceptionClass() syntax.
  2. Step 2: Check the correct usage for BadRequestException

    The correct syntax is throw new BadRequestException('message').
  3. Final Answer:

    throw new BadRequestException('Invalid input'); -> Option A
  4. 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

  1. 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).
  2. Step 2: Understand the normal return

    If no exceptions are thrown, the method returns the user with HTTP 200 status.
  3. Final Answer:

    200 if user found, 400 if ID missing, 404 if user not found -> Option A
  4. 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

  1. Step 1: Check how exceptions are thrown in NestJS

    Exceptions must be thrown using the throw keyword followed by new ExceptionClass().
  2. Step 2: Identify the missing part in the code

    The code calls ForbiddenException('Access denied') without throw and new, so it does nothing.
  3. Final Answer:

    Missing 'throw' keyword before the exception -> Option B
  4. 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

  1. Step 1: Understand how to customize exception response body

    Passing an object to super() in the exception constructor customizes the JSON response.
  2. 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.
  3. 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.
  4. Final Answer:

    class CustomForbiddenException extends ForbiddenException { constructor() { super({ message: 'Access denied', errorCode: 123 }); } } -> Option C
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard