Backend: Added docs & AGENTS.md
This commit is contained in:
1 parent
b3f2097b8b
commit
b3ab69cc22
8 files changed
+3082
No files matched your search
@@ -0,0 +1,143 @@
|
||||
# Error Handling
|
||||
|
||||
---
|
||||
|
||||
## 1. Architecture
|
||||
|
||||
The backend uses a **custom error class hierarchy** rooted in `CustomError` (extends `Error`) combined with an Express **global error-handling middleware** registered after all routes.
|
||||
|
||||
```
|
||||
Error (native)
|
||||
└── CustomError (base, 500)
|
||||
├── BadRequestError (400)
|
||||
├── ValidationError (400)
|
||||
├── UnauthorizedError (401)
|
||||
├── ForbiddenError (403)
|
||||
├── NotFoundError (404)
|
||||
├── ConflictError (409)
|
||||
└── InternalServerError (500)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Error Classes
|
||||
|
||||
All classes live under `errors/` and extend `CustomError`.
|
||||
|
||||
| Class | File | HTTP Status | Use Case |
|
||||
| --------------------- | ------------------------------- | ----------- | -------------------------------------------------------------- |
|
||||
| `CustomError` | `errors/CustomError.js` | 500 | Abstract base class |
|
||||
| `BadRequestError` | `errors/BadRequestError.js` | 400 | Missing or invalid request parameters |
|
||||
| `ValidationError` | `errors/ValidationError.js` | 400 | Semantic validation failures (named 422-style but returns 400) |
|
||||
| `UnauthorizedError` | `errors/UnauthorizedError.js` | 401 | Authentication required |
|
||||
| `ForbiddenError` | `errors/ForbiddenError.js` | 403 | Insufficient permissions |
|
||||
| `NotFoundError` | `errors/NotFoundError.js` | 404 | Resource not found |
|
||||
| `ConflictError` | `errors/ConflictError.js` | 409 | State conflict (e.g., duplicate resource) |
|
||||
| `InternalServerError` | `errors/InternalServerError.js` | 500 | Unexpected server-side failures |
|
||||
|
||||
### Base class implementation
|
||||
|
||||
```js
|
||||
class CustomError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = this.constructor.name;
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
statusCode() {
|
||||
return 500;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each subclass overrides `statusCode()` to return its specific HTTP code.
|
||||
|
||||
---
|
||||
|
||||
## 3. Global Error-Handling Middleware
|
||||
|
||||
**File:** `middleware/errorHandler.js`
|
||||
|
||||
```js
|
||||
module.exports = (err, req, res, next) => {
|
||||
if (err instanceof CustomError) {
|
||||
res.status(err.statusCode()).json({ message: err.message });
|
||||
logToFile(`Error (${err.statusCode()}) ${err.message}`);
|
||||
} else {
|
||||
logToFile(`Error (500) ${err}`);
|
||||
res.status(500).json({ message: 'Internal server error' });
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
**Behaviour:**
|
||||
|
||||
| Error type | Response status | Response body | Logged |
|
||||
| ------------------------ | ------------------ | ---------------------------------------- | -------------------------- |
|
||||
| `instanceof CustomError` | `err.statusCode()` | `{ "message": "<error message>" }` | Yes — error code + message |
|
||||
| Any other error | `500` | `{ "message": "Internal server error" }` | Yes — full error string |
|
||||
|
||||
The middleware is registered in `server.js` after all route handlers:
|
||||
|
||||
```js
|
||||
app.use('/api/v1', routes);
|
||||
app.use(errorHandler); // ← catches all thrown/next(err) errors
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Throwing Errors in Services
|
||||
|
||||
Services throw custom errors directly. Express catches them via the async flow (controllers use `async` handlers):
|
||||
|
||||
```js
|
||||
// In a service
|
||||
if (!id) {
|
||||
throw new BadRequestError("Entry id not provided");
|
||||
}
|
||||
|
||||
const entry = await Entry.findByPk(id);
|
||||
if (!entry) {
|
||||
throw new NotFoundError("Entry with the provided id was not found");
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** Most controller methods do not wrap calls in `try/catch`. They rely on the global error middleware. Some controllers (particularly `CollectionController`) still have inline `try/catch` blocks that return `500` directly — these predate the centralized error handling.
|
||||
|
||||
---
|
||||
|
||||
## 5. Logging Integration
|
||||
|
||||
All handled errors are written to `showy.log` via `LogService.logToFile()`:
|
||||
|
||||
```
|
||||
[2026-03-30 14:22:01] Error (404) Entry with the provided id was not found
|
||||
[2026-03-30 14:22:05] Error (500) ReferenceError: kill is not defined
|
||||
```
|
||||
|
||||
Format: `[YYYY-MM-DD HH:mm:ss] Error ({code}) {message}`
|
||||
|
||||
---
|
||||
|
||||
## 6. Error Response Contract
|
||||
|
||||
All error responses follow a consistent JSON shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Human-readable error description"
|
||||
}
|
||||
```
|
||||
|
||||
Some legacy controller handlers also use `{ "error": "..." }` — this inconsistency exists in older code paths that pre-date the `CustomError` system.
|
||||
|
||||
---
|
||||
|
||||
## 7. Unhandled Cases
|
||||
|
||||
| Scenario | Current behaviour |
|
||||
| --------------------------------------- | ------------------------------------------------------------------------------------- |
|
||||
| Sequelize `ValidationError` (ORM-level) | Falls through to the generic 500 handler since it is not an instance of `CustomError` |
|
||||
| Unhandled promise rejection | Logged to stderr by Node.js; not caught by Express middleware |
|
||||
| CORS preflight errors | Handled by inline CORS middleware before reaching the error handler |
|
||||
| Multer file upload errors | Caught inline in route handlers |
|
||||
Reference in new issue
Block a user