Updated the Obsidian docs-vault

This commit is contained in:
Mohammed Abad committed 2026-04-22 14:48:43 +01:00
1 parent 72fd77ee01
commit 260282a0e2
36 files changed
+3497 -144

No files matched your search

+70
View File
@@ -0,0 +1,70 @@
---
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
}
```