🦅 NestJS Beginner

What are Exception Filters in NestJS?

Answer

Exception Filters catch thrown exceptions and transform them into HTTP responses. NestJS has a built-in global exception filter that handles HttpException instances and returns an appropriate JSON response. Throw built-in exceptions: throw new NotFoundException('User not found'), throw new BadRequestException('Invalid data'), throw new UnauthorizedException(). Create custom filters implementing ExceptionFilter to handle domain-specific errors or reformat error responses. Apply with @UseFilters() or globally. The filter receives the exception and the host context, giving access to the request/response objects to send a custom error response. Custom filters are useful for handling ORM-specific errors like unique constraint violations.