Error Handling Strategy
Relevant source files
The following files were used as context for generating this wiki page:
The error handling strategy in this project is a multi-layered system designed to capture, standardize, and communicate failures across both the backend and frontend components. It relies on custom error classes and higher-order functions in the backend to ensure consistent API responses, while the frontend utilizes interceptors and state management to provide user feedback.
Backend Error Handling Architecture
The backend implements a centralized error handling mechanism to ensure that every failure results in a predictable JSON response structure. This is achieved through three primary components: a custom error class, a wrapper for asynchronous operations, and manual try-catch blocks within specific logic segments.
Centralized ApiError Class
The ApiError class extends the native JavaScript Error class to include properties relevant to HTTP communication. This standardization allows the system to pass structured metadata about a failure through the middleware chain.
| Property | Type | Description |
|---|---|---|
statusCode | Number | The HTTP status code (e.g., 400, 401, 404, 500) |
message | String | A human-readable description of the error |
errors | Array | Detailed validation errors or sub-errors |
success | Boolean | Always set to false for error instances |
data | Null | Placeholder for consistency with successful responses |
Sources: BACKEND/src/utils/ApiError.js:1-25
Async Middleware Wrapper (asynchandler)
To prevent unhandled promise rejections and repetitive try-catch blocks in controllers, the project uses an asynchandler wrapper. This higher-order function catches any error thrown within an asynchronous route and formats a standard JSON response.
const asynchandler = (fn) => async(req , res , next) => {
try {
await fn(req , res, next)
} catch (error) {
console.error("Error in async handler:", error);
let statusCode = error.statusCode || 500;
// Validation of status code range 100-599
res.status(statusCode).json({
success: false,
message: error.message
})
}
}
Sources: BACKEND/src/utils/asynchandler.js:1-24
Data Flow for Backend Errors
The following diagram illustrates how an error propagates from a controller through the asynchronous handler to the client.
This flow ensures that even unexpected runtime exceptions are caught and returned as a 500 Internal Server Error if no specific status code is provided. Sources: BACKEND/src/utils/asynchandler.js:4-21, BACKEND/src/controllers/user.controller.js:101-103
Authentication and Authorization Errors
The auth.middleware.js specifically handles security-related failures. It distinguishes between missing tokens, expired tokens, and malformed tokens to provide precise feedback.
| Error Scenario | HTTP Status | Message |
|---|---|---|
| Missing Token | 401 | "Unauthorized request" |
| Expired Token | 401 | "Token has expired" |
| Malformed/Invalid Token | 401 | "Invalid token format" |
| User Not Found | 401 | "Invalid Access Token" |
Frontend Error Handling and Feedback
The frontend handles errors by combining global interceptors for status codes and local state management within React components to display user-friendly messages.
Axios Interceptors and Service Layer
The api.js service uses Axios interceptors to process outgoing requests and catch incoming errors. When an API call fails, the service layer extracts the error message from the response data to be used by the calling component.
// Example of error extraction in services
export const login = async (email, password) => {
try {
const response = await api.post("/users/login", { email, password });
return response.data;
} catch (error) {
throw error.response?.data || error.message;
}
};
Sources: frontend/front/src/services/api.js:21-27
Component-Level State Management
React components use useState to track error states. This allows the UI to conditionally render error messages or styles when an API call fails.
- Articles Page: Sets an
errorstate string ifaxios.getfails, displaying "Failed to fetch articles. Try again later." Sources: frontend/front/src/Article/article.jsx:110-113 - Chatbot Page: Logs errors to the console and resets the
loadingstate to allow the user to retry. Sources: frontend/front/src/chatbot/chatbot.jsx:214-217 - Signup Page: Displays a specific
.error-messageelement if the signup API call throws an exception. Sources: frontend/front/src/signup/signup.jsx:27-30
Error Message Styling
Standardized CSS classes are used across the frontend to provide visual cues for errors, typically utilizing white or light-colored text against dark backgrounds in the "Bridge AI" theme.
| CSS Class | Location | Usage |
|---|---|---|
.error-text | article.css | Displays "Failed to fetch" messages in the Article list |
.error-message | signup.css | Displays validation or server errors in signup forms |
Sources: frontend/front/src/Article/article.css:104-108, frontend/front/src/signup/signup.jsx:43
Summary
The error handling strategy centers on the ApiError class and asynchandler in the backend to maintain a consistent API contract. On the frontend, errors are intercepted at the service layer and propagated to React component states, where they are rendered using specific UI containers. This end-to-end approach ensures that technical failures are logged for developers while remaining informative for end-users.