Skip to content
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

Closed
wants to merge 3 commits into from
Closed

Conversation

geetanjalichawla
Copy link
Contributor

@geetanjalichawla geetanjalichawla commented Dec 4, 2023

  • 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]

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

- 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]
Copy link

vercel bot commented Dec 4, 2023

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
wanderlust ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 5, 2023 6:23pm
wanderlust-backend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 5, 2023 6:23pm

@krishnaacharyaa
Copy link
Owner

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.
And you are presently violating 1, 4, 5th point of Community Guidelines
Once these are addressed we can consider this PR,
For now parking it.

@krishnaacharyaa krishnaacharyaa marked this pull request as draft December 4, 2023 16:55
@geetanjalichawla
Copy link
Contributor Author

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
Copy link
Contributor Author

@krishnaacharyaa

@krishnaacharyaa
Copy link
Owner

@geetanjalichawla Sure,

  1. You need to discuss the approach you are going to follow in the issue section (If you are following any resource share it and be specific of how you are planning to take the task), once we finalize a particular approach you can take it up (that should reduce your rework by 90% and saves lots of my time), this is the first part. If this is not done it really consumes both of our precious time.
  2. Then you need to just follow the simple 7 steps in the contributing guidelines

if you can give me more details i"ll fix the staging and file name issues

So for this,

  1. fixing the staging: You need to make sure only required changes are done (if you see diff of files in PR, more red i.e delete and changes, always shatters the confidence of the reviewer), and only required minimal changes are commited, here I see frontend's package-lock.json is also commited, how is that relevant to the present issue and PR?
  2. For file name we are using this-case than ThisCase that you need to follow

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 :)

@geetanjalichawla
Copy link
Contributor Author

// 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

@krishnaacharyaa
Copy link
Owner

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
#71 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Centralised Error Handling
3 participants