पाठ 21 / 32

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 परिभाषित करें।

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 लौटाएँ।
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');
});

त्वरित जाँच

त्वरित जाँच: handler में uncaught `throw new Error('x')` पर Fastify default में कौन सा status देता है?

  • 400
  • 500
  • 200
Answer

500 — statusCode के बिना errors 500 Internal Server Error बनते हैं।