NestJS

Lesson 05

Exception filters and error shape

Use exception filters when an API needs one response shape for logged and user-facing errors.

Good Code

http-exception.filter.ts
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from "@nestjs/common";

@Catch(HttpException)
export class ApiExceptionFilter implements ExceptionFilter {
  // The filter owns the public error response shape.
  catch(error: HttpException, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    const status = error.getStatus();

    response.status(status).json({
      statusCode: status,
      error: "REQUEST_FAILED",
      message: error.message,
    });
  }
}

Bad Code

reviews.controller.ts
import { Controller, Get, Param } from "@nestjs/common";

@Controller("reviews")
export class ReviewsController {
  @Get(":id")
  async findOne(@Param("id") id: string) {
    try {
      return await this.reviews.findOne(id);
    } catch (error) {
      // Raw errors can leak internal messages to clients.
      return { ok: false, error: String(error) };
    }
  }
}

Review Notes

What to review

Good Code

The good version puts API error formatting in a filter. Route methods can throw framework exceptions and still return a consistent JSON shape.

Bad Code

The bad version catches unknown errors inside a route and serializes them. Internal messages can leak to clients and logs may lose the original stack.

Takeaways

  • Exception filters should translate failures into consistent responses without leaking internal details.