1.8 KiB
1.8 KiB
title, tags
| title | tags | |||
|---|---|---|---|---|
| Error Handling |
|
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:
- CustomError subclasses →
{ error: name, message, statusCode } - Sequelize
ValidationError→ 400 with field-level messages SequelizeUniqueConstraintError→ 409 ConflictSequelizeForeignKeyConstraintError→ 400 Bad Request- 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:
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:
{
"error": "NotFoundError",
"message": "Entry not found",
"statusCode": 404
}