Handling ASYNC errors


const ExpressError = require("./ExpressError.js");
// HANDLING ASYNC ERROR MESSAGES
app.use((err, req, res, next) => {
  let { status = 500, message = " UNKNOWN ERROR OCCURRED" } = err;
  res.status(status).send(message);
});

// SHOW ROUTE
app.get("/chats/:id", async (req, res, next) => {
  let { id } = req.params;
  let chat = await Chat.findById(id);
  if (!chat) {
    next( new ExpressError(404, "chat not found"));
  }

  res.render("edit.ejs", { chat });

}); 



HERE IF WE SEND if(!chat){

    throw new ExpressError(404,"chat not found");
}

THEN THE REQUIRED ERROR MESSAGE IS NOT DISPLAYED.


HENCE,WE SEND IT THROUGH NEXT().


EXPRESS.JS

class ExpressError extends Error{

    constructor(status,message){
        super();
        this.status=status;
        this.message=message;
    }
}
module.exports=ExpressError;


IF THE LENGTH OF THE ID IS MORE THAN THE REQUIRED LENGTH THEN MONGODB ERROR OCCURS.



IF WE COMMENT OUT THE ERROR HANDLER AND SEND A REQUEST THEN AN EJS ERROR OCCURS.





Comments

Popular posts from this blog

DATABASE RELATIONSHIPS

ROUTING (GET /) home route

Query Strings