# Exception Handling — नेस्टजेएस

Source: https://www.geekswithgeeks.com/hi/nestjs/nestjs-exception-handling

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

## Built-in exceptions

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

```typescript
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 करें।

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