Error Handling
Pattern
Wrap async route handlers with asyncHandler and throw AppError for HTTP errors:
import { asyncHandler, AppError } from '../middleware/error.middleware.js';
router.get('/resource/:id', asyncHandler(async (req, res) => {
const item = await findItem(req.params.id);
if (!item) throw new AppError('Resource not found', 404);
res.json({ success: true, data: item });
}));
Response Format
Success
{ "success": true, "data": { ... } }
Error
{ "success": false, "error": "Resource not found" }
How It Works
asyncHandlerpasses a rejected promise from the handler to Express (.catch(next))- If the handler throws an
AppError, the error middleware (errorHandler) sends itsstatusCodeand message - Any other error is sent as a 500 with the error's message. A
stackfield is added only whenNODE_ENV=development - Unknown routes are answered by
notFoundHandlerwith a 404:{ "success": false, "error": "Not Found", "message": "Cannot GET /api/unknown" }
Error messages reach the client
The message of any thrown error is returned in the response, not only AppError messages. Do not put secrets, file paths or upstream response bodies in error messages.