# Error Handling — Fastify: High-Performance Node.js APIs बनाना

Source: https://www.skillbyai.com/hi/fastify/ff-error-handling

> Async handlers में errors throw करें, custom error classes define करें और error responses नियंत्रित करें।

## Error handling strategy

Route handlers में errors throw करें; Fastify का built-in error handler उन्हें पकड़ता है और appropriate status codes और responses return करता है।

## Custom error class

Status codes और payloads को control करने के लिए custom error class परिभाषित करें।

```javascript
class AppError extends Error {
  constructor(message, statusCode = 500) {
    super(message);
    this.statusCode = statusCode;
  }
}

fastify.get('/users/:id', async (req) => {
  const user = await findUser(req.params.id);
  if (!user) {
    throw new AppError('User not found', 404);
  }
  return user;
});

fastify.setErrorHandler((err, req, reply) => {
  const statusCode = err.statusCode || 500;
  reply.status(statusCode).send({ error: err.message });
});
```

## Async error handling

Fastify automatically async handlers में throw की गई errors को पकड़ता है—try/catch wrappers की ज़रूरत नहीं।

## Custom error handler

`setErrorHandler` handlers और hooks में throw हुए errors पकड़ता है।

- `error.statusCode` validation failure या `reply.code` से आता है।
- हमेशा एक जैसी JSON shape लौटाएँ।

```js
const fastify = require('fastify')();

fastify.setErrorHandler((error, request, reply) => {
  reply.code(error.statusCode || 500).send({
    ok: false,
    message: error.message
  });
});

fastify.get('/boom', async () => {
  throw new Error('kaboom');
});
```

त्वरित जाँच

**Quiz:** handler में uncaught `throw new Error('x')` पर Fastify default में कौन सा status देता है?

- [ ] 400
- [x] 500
- [ ] 200

*Answer:* 500. statusCode के बिना errors 500 Internal Server Error बनते हैं।
