-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat#1: Add centralized error handling and custom error middleware #71
Conversation
- Introduce a `catchError` function to wrap asynchronous functions with a centralized error catcher. - Implement an `ErrorMiddleware` to handle various types of errors, including MongoDB validation errors. - Create a custom `ErrorHandler` class to provide a consistent structure for handling errors. The `catchError` function simplifies error handling by using a common approach, while the `ErrorMiddleware` and `ErrorHandler` enhance error responses and provide a standardized way to handle errors throughout the application. Files added: - [catchError.js] - [ErrorMiddleWare.js] - [ErrorHandler.js]
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
Hi @geetanjalichawla, Thank you for the PR, How it works is, you will have to actually get it assigned to you first and then raise the PR, kindly go through the community guidelines once again. |
…are" This reverts commit 294a581.
alright thanks its going to be my first contribution as like this please help me out with the claiming thing how we can do it if you can give me more details i"ll fix the staging and file name issues |
@geetanjalichawla Sure,
So for this,
These are all clearly written in contributing guidelines, kindly go through it again if you feel confused, and if you feel any thing are not clearly mentioned in the same let me know, will be happy to make it more crystal clear :) |
// Stage 1: Custom ErrorHandler Class
// In the "utils/error-handler.js" file, a custom ErrorHandler class is defined to manage application-specific errors.
// This class extends the built-in Error class and introduces a statusCode property for handling HTTP status codes.
class ErrorHandler extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
}
}
// Export the custom ErrorHandler class
export default ErrorHandler;
// Stage 2: ErrorMiddleware Function
// In the "middleware/error-middleware.js" file, the ErrorMiddleware function is implemented.
// This middleware is designed to handle errors within the application.
// It checks if the error is a MongoDB validation error and formats the response accordingly.
// If it's another type of error, a generic error response with the appropriate status code is sent.
export const ErrorMiddleware = (err, req, res, next) => {
// Set default status code and message
let statusCode = err.statusCode || 500;
let message = err._message || err.message || "Internal server error";
// Log the error for debugging purposes
console.log({ err });
// Check if the error is a MongoDB validation error
if (err.name === "ValidationError") {
// Handling MongoDB validation errors
statusCode = 422; // Unprocessable Entity
// Extract validation error messages
const validationErrors = Object.values(err.errors).map((error) => error.message);
message = validationErrors[0] || "Validation error";
// Send a JSON response with validation errors
res.status(statusCode).json({
success: false,
message,
error: validationErrors,
});
} else {
// Handling other errors
// Send a JSON response with the error message
res.status(statusCode).json({
success: false,
message,
});
}
};
// Stage 3: catchError Higher-Order Function
// In the "utils/catch-error.js" file, the catchError function is defined as a higher-order function.
// This function catches asynchronous errors using Promise.resolve and forwards them to the error middleware.
export const catchError = (passedFunction) => async (req, res, next) => {
// Use Promise.resolve to catch errors in the asynchronous function
Promise.resolve(passedFunction(req, res, next)).catch(next);
};
// Stage 4: Integration with APIs
// These utility functions can be integrated into the APIs to handle errors effectively.
// Import the ErrorHandler class, ErrorMiddleware, and catchError functions into your API files
// and use them where necessary to ensure consistent error handling throughout the application.
// Further details and adjustments can be made based on specific project requirements. @krishnaacharyaa as i have already done the code so this is my approach as well as code for the refactoring |
We dont appreciate AI chatgpt answers, if you can fine tune it based on the requirments or can come up with your own solution, will be very happy to proceed, p.s: It just makes me feel waste of time explaining you stuff clearly in exchange to my worthy time |
catchError
function to wrap asynchronous functions with a centralized error catcher.ErrorMiddleware
to handle various types of errors, including MongoDB validation errors.ErrorHandler
class to provide a consistent structure for handling errors.The
catchError
function simplifies error handling by using a common approach, while theErrorMiddleware
andErrorHandler
enhance error responses and provide a standardized way to handle errors throughout the application.Files added:
Summary
This pull request introduces a catchError function to wrap asynchronous functions with a centralized error catcher, enhancing the application's error handling. Additionally, an ErrorMiddleware and a custom ErrorHandler class have been implemented to handle various types of errors, including MongoDB validation errors.
Description
Certainly, it seems like you're working on a pull request to enhance error handling in an application. Here's a draft for your pull request message:
Title:
Introduce Centralized Error Handling with catchError Function
Summary:
This pull request introduces a catchError function to wrap asynchronous functions with a centralized error catcher, enhancing the application's error handling. Additionally, an ErrorMiddleware and a custom ErrorHandler class have been implemented to handle various types of errors, including MongoDB validation errors.
Description:
In response to the need for a more streamlined error handling approach, this pull request addresses the following key points:
1. catchError Function ([catchError.js]):
The catchError function is introduced to simplify error handling for asynchronous functions.
It wraps asynchronous functions, providing a centralized mechanism for catching errors.
This promotes a consistent error handling approach throughout the application.
2. ErrorMiddleware ([ErrorMiddleWare.js]):
An ErrorMiddleware has been implemented to handle different types of errors.
Special attention is given to MongoDB validation errors, ensuring comprehensive error coverage.
This middleware enhances error responses, providing a more informative and user-friendly experience.
3. Custom ErrorHandler Class ([ErrorHandler.js]):
A ErrorHandler class has been created to maintain a consistent structure for handling errors.
This class facilitates a standardized way to handle errors across the application.
Images
Include any relevant images or diagrams that can help reviewers visualize the changes, if applicable
Issue(s) Addressed
Enter the issue number of the bug(s) that this PR fixes
Prerequisites