Overview
DEMET Backend API implements centralized error handling to provide consistent, informative error responses across all endpoints.All errors follow a standardized format and use appropriate HTTP status codes for easy debugging and client-side error handling.
Error Response Format
All error responses follow this consistent structure:Some endpoints may include additional fields like
role or error depending on the context.HTTP Status Codes
The API uses standard HTTP status codes to indicate the type of error:| Status Code | Meaning | Use Cases |
|---|---|---|
| 200 | OK | Successful operation |
| 201 | Created | Resource created successfully |
| 400 | Bad Request | Validation errors, malformed data, business logic violations |
| 401 | Unauthorized | Missing/invalid token, wrong credentials, insufficient permissions |
| 404 | Not Found | Resource not found |
| 409 | Conflict | Duplicate data, resource already exists |
| 500 | Internal Server Error | Unexpected errors, database connection issues |
| 503 | Service Unavailable | Database connection refused |
Error Types
1. Authentication Errors (401)
These errors occur when JWT token validation fails:Token Not Sent
Token Not Sent
Occurs when the request doesn’t include an Source:
access_token cookie./middleware/verifyToken.js:5-7Response:Invalid or Expired Token
Invalid or Expired Token
Occurs when the JWT signature is invalid or the token has expired.Source:
/middleware/verifyToken.js:9-11Response:Wrong Credentials
Wrong Credentials
Occurs during login when email or password is incorrect.Source:
/controller/auth.controller.js:77-83Responses:2. Authorization Errors (401)
These errors occur when a user lacks the required role/permissions:/middleware/rolAccess.js:14-18
Response:
3. Validation Errors (400)
Zod validation errors occur when request data doesn’t match the schema:/middleware/validate.js:3-13
Example Validation Errors
Example Validation Errors
Invalid email format:Password too short:Invalid role:Date validation (custom rule):Schema:
/validator/reserve.schema.js:23-294. Database Errors
The API uses a centralizederrorHandler function to map database errors to HTTP responses:
/util/errorHandler.js:1-67
Error Handler Flow:
- Check for native PostgreSQL error codes
- Search for custom error text from stored procedures
- Throw a standardized
AppErrorwith appropriate status code - If no match, default to 500 Internal Server Error
AppError Class
Custom error class that extends the nativeError class:
/util/AppError.js:2-12
Properties:
message- Human-readable error descriptionstatusCode- HTTP status code to returnisOperational- Flag indicating this is a known, handleable error (not a bug)
Common Database Error Scenarios
Unique Constraint Violation (409)
Unique Constraint Violation (409)
Occurs when trying to create a resource with a duplicate unique field.Native PostgreSQL error:Custom stored procedure errors:
"EMAIL EN USO"- Duplicate email during employee registration"CODIGO DE RESERVA EN USO"- Duplicate reservation ID"VALORES DUPLICADOS"- Duplicate ID or cedula
Resource Not Found (404)
Resource Not Found (404)
Occurs when querying or updating a non-existent resource.Examples:
"RESERVA NO ENCONTRADA""SOCIO NO ENCONTRADO""ESPACIO NO ENCONTRADO""TARIFA NO ENCONTRADA""EMAIL DESCONOCIDO"
Business Logic Violations (400)
Business Logic Violations (400)
Occurs when data violates business rules enforced by stored procedures.Examples:
"AFORO MAXIMO SOBREPASADO"- Too many guests for space capacity"EL INICIO DE LA RESERVA NO PUEDE SER MAYOR A SU CULMINACION"- Invalid date range"NO SE PERMITE VALORES NEGATIVOS"- Negative numbers not allowed"Formato de dato inválido"- PostgreSQL type mismatch
Database Connection Errors (503)
Database Connection Errors (503)
Occurs when the API cannot connect to PostgreSQL.Response:
Error Handling in Controllers
Controllers catch errors from services and format them appropriately:/controller/reserve.controller.js:4-18
Pattern:
- Try to execute service logic
- Catch any errors (from
errorHandleror unexpected errors) - Extract
statusCodefromAppError(default to 500 if undefined) - Return error response with status code and message
Error Handling in Services
Services callerrorHandler when database operations fail:
/service/reserve.service.js:5-42
Complete Error Flow
Here’s how errors propagate through the system:Error Response Examples by Endpoint
Best Practices
Use Appropriate Status Codes
Always return the correct HTTP status code (400 for validation, 401 for auth, 404 for not found, etc.)
Provide Clear Messages
Error messages should be descriptive and actionable for debugging.
Centralize Error Handling
Use
errorHandler and AppError consistently across all services.Log Errors
Use
console.log(error) in controllers to track errors (consider structured logging in production).Handling Errors on the Client
Example: React Error Handling
Example: React Error Handling
Next Steps
Architecture
Understand how controllers, services, and middleware work together.
Security
Learn about authentication and authorization errors in detail.