पाठ 12 / 33

Exception Handling

HTTP exceptions throw करें और global error handling का उपयोग करें।

Built-in exceptions

NestJS BadRequestException, NotFoundException, UnauthorizedException आदि देता है जो automatically सही HTTP status set करते हैं।

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

Errors को catch करने और ऐप भर में globally format करने के लिए ExceptionFilter को implement करें।

@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());