diff --git a/IT18021080/Telemedicine-Chat-App/backend/middleware/errorMiddleware.js b/IT18021080/Telemedicine-Chat-App/backend/middleware/errorMiddleware.js new file mode 100644 index 0000000000000000000000000000000000000000..65fd039de6552b844b69526a81cf1577ea9996c8 --- /dev/null +++ b/IT18021080/Telemedicine-Chat-App/backend/middleware/errorMiddleware.js @@ -0,0 +1,18 @@ +const notFound = (req, res, next) => { + //connect with server.js + const error = new Error(`Not Found - ${req.originalUrl}`); + res.status(404); + next(error); +}; + +const errorHandler = (err, req, res, next) => { + const statusCode = res.statusCode === 200 ? 500 : res.statusCode; + res.status(statusCode); + res.json({ + message: err.message, + stack: process.env.NODE_ENV === "production" ? null : err.stack, + + }); +}; + +module.exports = { notFound, errorHandler }; \ No newline at end of file diff --git a/IT18021080/Telemedicine-Chat-App/backend/server.js b/IT18021080/Telemedicine-Chat-App/backend/server.js index e94cb8f5eaf2254c0462521230e92be1efd2db3c..71200e79e8e64d7949d5e337f6267b942c2be182 100644 --- a/IT18021080/Telemedicine-Chat-App/backend/server.js +++ b/IT18021080/Telemedicine-Chat-App/backend/server.js @@ -5,6 +5,7 @@ const { chats } = require("./data/data"); const connectDB = require("./config/db"); const colors = require("colors"); const userRoutes = require("./routes/userRoutes"); +const { notFound,errorHandler} = require("./middleware/errorMiddleware"); dotenv.config(); @@ -21,6 +22,10 @@ app.get("/", (req, res) => { app.use("/api/user", userRoutes); +//API Error Handling +app.use(notFound); +app.use(errorHandler); + const PORT = process.env.PORT || 5000; app.listen(5000, console.log(`Server Started on PORT ${PORT}`.yellow.bold)); \ No newline at end of file