Learn NestJS · 6/14

Graceful Error Handling and Logging

9 min read

Graceful Error Handling and Logging in NestJS NestJS handle errors?

Imagine you're building a brand new, gleaming skyscraper (your application). Everything looks perfect, the elevators are swift, and the views are amazing. But what happens when a window cracks or the plumbing springs a leak? Do you just let the water pour out and hope no one notices? Of course not! You have a maintenance crew (error handling) ready to swoop in, assess the damage, and fix it before it causes a major flood.

In the world of web applications, things go wrong. Users will input incorrect data, external services will fail, and sometimes, our own code will have a "moment." How our application responds to these errors is crucial. Crashing and burning with a cryptic error message is the equivalent of that major flood. Graceful error handling is our skilled maintenance crew, catching issues, logging them for later analysis, and presenting the user with a clean, understandable response.

This guide will walk you through how to set up a robust error handling and logging system in your NestJS application, so you can keep your skyscraper standing tall and your users happy.


1. Standard Exceptions and the HttpException Class 🕵️‍♀️

The Problem: When a request comes into your NestJS application and something goes wrong, you need a standardized way to tell the client, "Hey, I can't fulfill this request, and here's why." Just throwing a generic "500 Internal Server Error" for everything is like a doctor telling every patient, "You're sick." It's not very helpful. We need to be more specific.

The Solution: HttpException

NestJS provides a built-in HttpException class that allows us to create more descriptive HTTP error responses. It's the foundation of NestJS's error handling.

Under the hood, when you throw an HttpException, NestJS catches it and automatically formats a JSON response with the details you provide. This saves you from manually crafting error objects in every single controller.

Let's see it in action. Imagine we have a CatsController and we want to handle the case where a cat with a specific ID is not found.

typescript
// src/cats/cats.controller.ts
import { Controller, Get, Param, ParseIntPipe, NotFoundException } from '@nestjs/common';
import { CatsService } from './cats.service';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    const cat = this.catsService.findOne(id);
    if (!cat) {
      throw new NotFoundException(`Cat with ID ${id} not found`);
    }
    return cat;
  }
}

In this example, if catsService.findOne(id) returns undefined, we throw a NotFoundException. This is actually a pre-built class that extends HttpException. NestJS will then automatically send a 404 Not Found response that looks something like this:

json
{
  "statusCode": 404,
  "message": "Cat with ID 101 not found",
  "error": "Not Found"
}

Pretty neat, right? NestJS comes with a whole family of these standard exception classes for common HTTP errors, like:

  • BadRequestException (400)
  • UnauthorizedException (401)
  • ForbiddenException (403)
  • NotFoundException (404)
  • And many more!

Fun Fact: The HTTP status code 418 I'm a teapot was originally an April Fools' joke from 1998 but has become a beloved "Easter egg" among developers for handling absurd or impossible requests. teapot?


2. Creating Custom Business Exceptions 🎩

The Problem: The built-in exceptions are great for standard HTTP errors, but what about errors specific to your application's logic? For instance, what if a user tries to purchase an item that is out of stock? This isn't a "Not Found" or "Bad Request" in the traditional sense. It's a specific business rule that has been violated.

The Solution: Custom Exceptions

For these scenarios, we can create our own custom exceptions by extending the HttpException class. This allows us to create a more expressive and maintainable codebase.

Let's imagine we're building an e-commerce application and need an InsufficientStockException.

typescript
// src/common/exceptions/insufficient-stock.exception.ts
import { HttpException, HttpStatus } from '@nestjs/common';

export class InsufficientStockException extends HttpException {
  constructor(itemId: string) {
    super(`Insufficient stock for item ${itemId}`, HttpStatus.CONFLICT);
  }
}

Here, we've created a new exception class. When we instantiate it, we pass a message and an HTTP status code to the parent HttpException constructor. HttpStatus.CONFLICT (409) is a good choice here, as the request couldn't be completed due to a conflict with the current state of the resource.

Now, we can use this in our ProductsController:

typescript
// src/products/products.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { ProductsService } from './products.service';
import { PurchaseProductDto } from './dto/purchase-product.dto';
import { InsufficientStockException } from '../common/exceptions/insufficient-stock.exception';

@Controller('products')
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Post('purchase')
  purchase(@Body() purchaseProductDto: PurchaseProductDto) {
    const hasStock = this.productsService.checkStock(purchaseProductDto.productId);
    if (!hasStock) {
      throw new InsufficientStockException(purchaseProductDto.productId);
    }
    // Proceed with purchase logic...
    return { message: 'Purchase successful!' };
  }
}

When this exception is thrown, NestJS will produce the following response:

json
{
  "statusCode": 409,
  "message": "Insufficient stock for item ABC-123"
}

By creating custom exceptions, we make our code easier to read and understand. When someone sees throw new InsufficientStockException(), they know exactly what's going on without needing to decipher a generic error.


3. Exception Filters: Catching and Formatting Errors Globally 🥅

The Problem: So far, we've been throwing exceptions, and NestJS has been catching them and formatting a default response. But what if we want to customize that response? Maybe we want to add a timestamp, or a unique request ID for tracking. Modifying every throw statement would be a nightmare.

The Solution: Exception Filters

Exception filters allow you to intercept unhandled exceptions and take full control over the response that is sent back to the client. They are a powerful way to centralize your error handling logic.

Let's create a global exception filter that will catch all HttpException instances and format the response in a consistent way.

typescript
// src/common/filters/http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
        message: exception.message,
      });
  }
}

Let's break this down:

  • The @Catch(HttpException) decorator tells NestJS that this filter should only be applied to exceptions of type HttpException.
  • The catch method is where the magic happens. It receives the exception object and the host (which gives us access to the request and response objects).
  • Inside the catch method, we extract the necessary details and craft our custom JSON response.

To apply this filter globally, we need to register it in our main application file.

typescript
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new HttpExceptionFilter()); // <-- Apply the filter here
  await app.listen(3000);
}
bootstrap();

Now, any time an HttpException is thrown anywhere in our application, this filter will intercept it and format the response according to our new structure. For example, our previous NotFoundException would now look like this:

json
{
  "statusCode": 404,
  "timestamp": "2026-02-25T12:15:00.000Z",
  "path": "/cats/101",
  "message": "Cat with ID 101 not found"
}

This gives us a consistent and more informative error response across our entire API.


4. Implementing a Structured Global Logging Service 📝

The Problem: When an error occurs in a production environment, we need to know about it. Simply sending a response to the user isn't enough. We need to log these errors so that we can analyze them later, debug issues, and monitor the health of our application. Console logging is fine for development, but in production, we need something more robust and structured.

The Solution: A Custom Logging Service

NestJS has a built-in logger, but for production applications, you'll often want more control over the log format and output. Creating a custom logger service allows us to implement structured logging (usually in JSON format), which is much easier to parse and analyze with log management tools.

First, let's create a simple custom logger.

typescript
// src/common/logger/my-logger.service.ts
import { Injectable, Scope, ConsoleLogger } from '@nestjs/common';

@Injectable({ scope: Scope.TRANSIENT })
export class MyLogger extends ConsoleLogger {
  error(message: any, stack?: string, context?: string) {
    // Here you could format the log message as JSON and send it to a logging service
    super.error.apply(this, arguments);
  }
}

In a real-world scenario, instead of super.error, you would use a library like winston or pino to format the log as JSON and send it to a destination like a file, a database, or a cloud logging service (like Datadog or Sentry).

Now, let's integrate this logger into our HttpExceptionFilter.

typescript
// src/common/filters/http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, Inject } from '@nestjs/common';
import { Request, Response } from 'express';
import { MyLogger } from '../logger/my-logger.service';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly logger: MyLogger) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    // ... (same as before)

    const status = exception.getStatus();
    const message = exception.message;

    this.logger.error(`[${request.method}] ${request.url} - ${status} - ${message}`);

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
        message: message,
      });
  }
}

And update our main.ts to provide the logger to the filter.

typescript
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { MyLogger } from './common/logger/my-logger.service';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: new MyLogger(),
  });
  app.useGlobalFilters(new HttpExceptionFilter(app.get(MyLogger)));
  await app.listen(3000);
}
bootstrap();

Now, every time an HttpException is caught, not only do we send a formatted response to the user, but we also log the error. This is invaluable for debugging and monitoring our application in a live environment. Imagine your application is a self-driving car. Logging is the "black box" that records everything, so if something goes wrong, you can replay the events and understand what happened.

By combining custom exceptions, global exception filters, and a structured logging service, you can build a resilient and maintainable NestJS application that handles errors gracefully and provides you with the insights you need to keep it running smoothly.


Further Reading & References 📚

Challenge

Your task is to implement a complete, production-ready error handling and logging mechanism in a NestJS application. You will need to create a custom business logic exception, a structured logger service, and a global exception filter that ties them together.

Requirements:

  1. Create a Custom Exception: Define a class named ProductOutOfStockException. This exception should extend the built-in HttpException and be used when an operation fails due to insufficient stock. It must use the HttpStatus.CONFLICT (409) status code.

  2. Create a Custom Logger Service: Implement a class named CustomLogger that is injectable (@Injectable()) and conforms to the LoggerService interface. For this challenge, you only need to provide a meaningful implementation for the error method; other methods can be empty stubs.

  3. Create a Global Exception Filter: Implement a class named AllExceptionsFilter that implements the ExceptionFilter interface and is decorated to catch all exceptions (@Catch()).

    • This filter must inject and use your CustomLogger service.
    • Inside the catch method, it must differentiate between HttpException instances and all other unhandled exceptions.
    • It must use the CustomLogger to log the error details.
    • Finally, it must format and send a standardized JSON response to the client with the following structure: { "statusCode": number, "timestamp": string, "path": string, "message": string }.

Expected result

The final code should correctly implement three classes as described:

  1. ProductOutOfStockException

    • Must correctly extend HttpException.
    • The constructor must call super('Product is out of stock', HttpStatus.CONFLICT);.
  2. CustomLogger

    • Must be decorated with @Injectable().
    • Must correctly implement the LoggerService interface.
    • The error method should be implemented, even if it's a simple console.log.
  3. AllExceptionsFilter

    • Must be decorated with @Catch().
    • The constructor must correctly inject the CustomLogger service (e.g., private readonly logger: CustomLogger).
    • The catch method must perform the following logic:
      • Determine the status and message.
      • If exception instanceof HttpException, use exception.getStatus() and exception.getResponse().
      • Otherwise, default the status to HttpStatus.INTERNAL_SERVER_ERROR and provide a generic message.
      • Call this.logger.error() with the error message and stack trace.
      • Create a response body object matching the specified format: { statusCode, timestamp, path, message }.
      • Use response.status(status).json(responseBody) to send the final response.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.