hiteshchoudhary / chai-backend

A video series on chai aur code youtube channel
4.69k stars 697 forks source link

error response should be formatted like response but its not avaible #146

Closed afaqkhan707 closed 1 month ago

afaqkhan707 commented 1 month ago

Solution..

`const errorHandler = (err, req, res, next) => { console.error(err.stack); const statusCode = err.statusCode || 500; const errorMessage = err.errorMessage || "Internal Server Error"; const error = err.error || null;

res.status(statusCode).json({
    statusCode,
    errorMessage,
    error
});

};

export { errorHandler }; ` create a middlware of errorhandler

Modify ApiError.js file and paste below code

`class ApiError extends Error { constructor( statusCode, errorMessage = "Something went wrong", error = null, stack = "" ) { super(errorMessage); this.statusCode = statusCode; this.errorMessage = errorMessage; this.error = error; // This should capture additional error details this.success = false;

    if (stack) {
        this.stack = stack;
    } else {
        Error.captureStackTrace(this, this.constructor);
    }
}

}

export { ApiError }; **in app.js file use this middelware** and pasteapp.use(errorHandler); user.controller.js if (existedUser) { throw new ApiError(409, "User email already exists"); } now this error will look like this { "statusCode": 400, "errorMessage": "Invalid email format", "error": { "field": "email", "error": "The email address is not in a valid format" } }`