पाठ 19 / 30
Error Handling
Gracefully error को handle करें और error responses को control करें।
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 की ज़रूरत नहीं।