Lesson 12 / 33

Exception Handling

Throw HTTP exceptions and use global error handling.

Built-in exceptions

NestJS provides BadRequestException, NotFoundException, UnauthorizedException, etc. that automatically set the right HTTP status.

import { NotFoundException, BadRequestException } from '@nestjs/common';

@Get(':id')
findOne(@Param('id') id: string) {
  const user = this.usersService.findOne(id);
  if (!user) {
    throw new NotFoundException(`User ${id} not found`);
  }
  return user;
}

Global exception filter

Implement ExceptionFilter to catch and format errors globally across your app.

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception instanceof HttpException ? exception.getStatus() : 500;

    response.status(status).json({
      statusCode: status,
      message: exception instanceof Error ? exception.message : 'Internal error'
    });
  }
}

// app.useGlobalFilters(new AllExceptionsFilter());