Error Handling (Error Handling)
Error Handling: مدیریت خطا در Express.js ⚠️
Error Handling برای مدیریت خطاها در Express استفاده میشه. بیایید یاد بگیریم!
Error Middleware:
const express = require('express');
const app = express();
// Route با error
app.get('/user/:id', (req, res, next) => {
const userId = req.params.id;
if (!userId) {
const error = new Error('User ID is required');
error.status = 400;
return next(error); // Pass error to error handler
}
res.json({ userId });
});
// Error handling middleware (باید آخر باشه!)
app.use((err, req, res, next) => {
const status = err.status || 500;
res.status(status).json({
error: {
message: err.message || 'Internal Server Error',
status: status
}
});
});
Try-Catch در Async Functions:
const express = require('express');
const app = express();
// با async/await
app.get('/users/:id', async (req, res, next) => {
try {
const user = await getUserById(req.params.id);
if (!user) {
throw new Error('User not found');
}
res.json(user);
} catch (error) {
next(error); // Pass to error handler
}
});
// یا با wrapper function
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
app.get('/users/:id', asyncHandler(async (req, res) => {
const user = await getUserById(req.params.id);
res.json(user);
}));
✅ یاد گرفتید: Error Handling برای نوشتن کد ایمن ضروریه!
آماده رفتن به درس بعدی هستید؟
این درس را به پایان رساندید و میتوانید به درس بعدی بروید.