Add ExpressError
EXPRESSERROR.JS IS CREATED IN UTILS FOLDER
class ExpressError extends Error {
constructor(statusCode, message) {
super();
this.statusCode = statusCode;
this.message = message;
}
}
module.exports = ExpressError;
IN APP.JS
const ExpressError = require("./utils/ExpressError.js");
(*) FOR EVERY INVALID REQUEST:
app.all("*",(req,res,next)=>{
next(new ExpressError(404,"Page not Found!?"));
})
app.use((err, req, res, next) => {
let { statusCode = 500, message = "something went wrong" } = err;
res.status(statusCode).send(message);
});
HERE WHILE CREATING NEW LISTING, IF NO CONTENT IS ADDED INTO THE FIELDS WE CAN MANIPULATE THE ERRORS.
app.post(
"/listings",
wrapAsync(async (req, res, next) => {
if(!req.body.listing){
throw new ExpressError(400,"send valid data!")
}
const newListing = new Listing(req.body.listing);
await newListing.save();
res.redirect("/listings");
})
);
SAME WHILE UPDATING
// UPDATE ROUTE
app.put("/listings/:id", wrapAsync(async (req, res) => {
if(!req.body.listing){
throw new ExpressError(400,"send valid data!")
}
let { id } = req.params;
await Listing.findByIdAndUpdate(id, { ...req.body.listing });
res.redirect(`/listings/${id}`);
}));



Comments
Post a Comment