Troubleshooting
Relevant source files
The following files were used as context for generating this wiki page:This document provides a technical overview of the error handling and troubleshooting mechanisms within the E-Commerce application. It covers both the backend API's centralized error management and the frontend's approach to user-facing error reporting. The system is designed to catch, classify, and respond to various issues, from invalid user input and database errors to server-side exceptions and failed API requests.
Troubleshooting involves understanding the flow of requests from the frontend, through backend validation and security middleware, to the final error handling middleware. On the client side, errors are typically surfaced to the user via toast notifications, providing immediate feedback on their actions.
Backend Error Handling
The backend, built with Express.js, employs a multi-layered approach to handling errors, including security measures, input validation, and a centralized error-handling middleware.
Sources: backend/app.js, backend/middleware/error.js, backend/middleware/validator.js
General Error Flow
All API requests pass through a series of middleware before reaching the route handlers. If any middleware or route handler passes an error to next(), it is caught by the final ErrorHandler middleware, which formats and sends the final error response to the client.
The following diagram illustrates the high-level error handling flow in the backend.
Sources: backend/app.js:14-40, backend/app.js:141
Central Error Handler (error.js)
The core of the backend's error strategy is the ErrorHandler middleware, which is the last middleware registered in app.js. It is responsible for catching all errors passed from other parts of the application and standardizing the response format.
It specifically handles several common error types by name or code, providing more user-friendly messages. If an error is not one of these specific types, it defaults to a 500 Internal Server Error.
| Error Name / Code | Status Code | Custom Message (Vietnamese) | Description |
|---|---|---|---|
CastError | 400 | Không tìm thấy tài nguyên với id này.. Không hợp lệ ${err.path} | Occurs when a MongoDB document ID is malformed. |
11000 (Duplicate Key) | 400 | Khóa đã nhập trùng lặp ${Object.keys(err.keyValue)} | Occurs on a unique index violation in MongoDB. |
JsonWebTokenError | 400 | url của bạn không hợp lệ vui lòng thử lại | Triggered by a malformed or invalid JWT. |
TokenExpiredError | 400 | url của bạn không hợp lệ vui lòng thử lại ! | Triggered when a JWT has expired. |
Sources: backend/middleware/error.js:3-30, backend/app.js:141
Input Validation (validator.js)
Before requests reach their controllers, many go through validation using express-validator. The validator.js middleware defines rule sets for various operations like user registration, login, and product creation.
The validate function runs the specified validations. If any validation fails, it aggregates the error messages and passes a new ErrorHandler instance with a 400 status code to the central error handler.
This diagram shows the input validation process.
Security and Rate Limiting
Several middleware in app.js contribute to system stability and can be a source of blocked requests, which can be perceived as errors by a client.
- Rate Limiting:
express-rate-limitis configured to allow a maximum of 100 requests per 15 minutes from a single IP address. Exceeding this limit results in a429 Too Many Requestsresponse with the message "Too many requests from this IP, please try again later." - Security Headers:
helmetapplies various security headers to prevent attacks like XSS. - CORS:
corsis configured to only allow requests from the specifiedFRONTEND_URL(e.g.,http://localhost:3000), blocking requests from other origins. - NoSQL Injection Sanitization:
express-mongo-sanitizeremoves characters like$and.from request bodies to prevent NoSQL injection attacks.
Sources: backend/app.js:19-25, backend/app.js:34-37
Frontend Error Reporting
The React frontend uses react-toastify as its primary mechanism for displaying error messages to the user. Errors are typically caught in component logic, either from client-side validation or from failed API calls managed through Redux.
Sources: frontend/src/components/Shop/CreateProduct.jsx, frontend/src/components/UserOrderDetails.jsx, frontend/src/components/Checkout/Checkout.jsx, frontend/src/components/Products/ProductDetails.jsx
User Feedback with react-toastify
Toast notifications provide non-intrusive, temporary feedback. This pattern is used consistently across the application for both success and error messages.
| Component | Scenario | Trigger |
|---|---|---|
CreateProduct.jsx | Failed product creation. | useEffect hook listening to error in the Redux products state. |
CreateProduct.jsx | Missing required fields on submit. | Client-side validation check in handleSubmit. |
ProductDetails.jsx | Adding an item that is already in the cart. | addToCartHandler checks if cart.some((i) => i.id === data.id). |
ProductDetails.jsx | Adding an out-of-stock product to the cart. | addToCartHandler checks if data.stock < 1. |
Checkout.jsx | Applying an invalid or non-existent coupon code. | handleSubmit function after an axios call to the coupon endpoint fails. |
Checkout.jsx | Proceeding to payment with an incomplete address. | paymentSubmit checks if address fields are empty. |
UserOrderDetails.jsx | Failed review submission. | catch block of the axios.put call in reviewHandler. |
Sources: frontend/src/components/Shop/CreateProduct.jsx:31-33, frontend/src/components/Shop/CreateProduct.jsx:62-65, frontend/src/components/Products/ProductDetails.jsx:43-45, frontend/src/components/Checkout/Checkout.jsx:78-81, frontend/src/components/UserOrderDetails.jsx:50-52
Frontend Error Handling Flow
The following sequence diagram shows a typical error flow when a user action fails, such as creating a new product with invalid data.
This diagram illustrates how state management with Redux is central to propagating API errors back to the UI components for display.
Sources: frontend/src/components/Shop/CreateProduct.jsx:29-35, frontend/src/components/Shop/CreateProduct.jsx:76-78