# Exception Handling — NestJS: Scalable Node.js APIs बनाना

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

> Built-in HTTP exceptions throw करें और global exception filter से errors को एक समान format करें।

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

## HTTP exceptions throw करना

built-in exception throw करें, response Nest बना देता है।

- `NotFoundException` का status 404 है।
- आपका दिया message `message` field बनता है।

```ts
import { Controller, Get, NotFoundException, Param } from '@nestjs/common';

@Controller('books')
export class BooksController {
  @Get(':id')
  find(@Param('id') id: string) {
    throw new NotFoundException(`Book ${id} not found`);
  }
}
```

Output:

```
{"message":"Book 5 not found","error":"Not Found","statusCode":404}
```

त्वरित जाँच

**Quiz:** exception filter पर बिना arguments वाला `@Catch()` क्या पकड़ता है?

- [ ] सिर्फ़ HttpException
- [x] हर thrown exception
- [ ] सिर्फ़ validation errors

*Answer:* हर thrown exception. खाली `@Catch()` किसी भी exception type के लिए catch-all filter है।
