--- title: Error Handling tags: - backend - errors - middleware --- # Error Handling ## Overview All errors flow through a central error handler middleware at the end of the Express pipeline. Custom error classes extend a base `CustomError` for consistent API responses. ## Error Classes All in `backend/errors/`: | Class | HTTP Status | File | |---|---|---| | `CustomError` | 500 | `CustomError.js` (base class) | | `BadRequestError` | 400 | `BadRequestError.js` | | `ValidationError` | 400 | `ValidationError.js` | | `NotFoundError` | 404 | `NotFoundError.js` | | `ConflictError` | 409 | `ConflictError.js` | | `ForbiddenError` | 403 | `ForbiddenError.js` | | `UnauthorizedError` | 401 | `UnauthorizedError.js` | | `InternalServerError` | 500 | `InternalServerError.js` | All extend `CustomError` which extends `Error`. Each sets `this.statusCode` and `this.name`. ## Error Handler Middleware > [!info] File: `backend/middleware/errorHandler.js` Catches and normalizes all errors: 1. **CustomError subclasses** → `{ error: name, message, statusCode }` 2. **Sequelize `ValidationError`** → 400 with field-level messages 3. **`SequelizeUniqueConstraintError`** → 409 Conflict 4. **`SequelizeForeignKeyConstraintError`** → 400 Bad Request 5. **Generic errors** → 500 Internal Server Error All errors are logged via `logService.logToFile()`. ## Async Wrapper > [!info] File: `backend/utils/asyncWrapper.js` Wraps async route handlers to catch rejected promises: ```js const asyncWrapper = (fn) => (req, res, next) => { fn(req, res, next).catch(next); }; ``` All controller methods are wrapped with this before being passed to Express routes. ## Response Format Error responses follow this structure: ```json { "error": "NotFoundError", "message": "Entry not found", "statusCode": 404 } ```