The error is being handled by express inbuilt error handler. But I want it to run my custom handler on catch of an error. Here is the code: miscellaneousAPI.js:
router.get("/exception", async (req, res, next) => {
try {
let ele = {};
//delibrately causing an error.
const ele2 = ele.map((i) => i);
res.status(200).send({ data: ele2 });
} catch (error) {
next(error);
}
});
app.get("/", (req, res) => {
res.status(200).send({ status: "ok" });
});
app.use((req, res) => {
res.status(404).send({
error: true,
message: "This route is not defined. Please try specified ones.",
});
});
app.use((error, req, res) => {
const errMsg = error.message || "Something went wrong";
res.status(error.statusCode).json({
success: false,
status: error.statusCode,
message: errMsg
});
});
I tried other answers on internet but my code is correct according to those. Please help me.