Skip to content

Commit

Permalink
add global api error handler
Browse files Browse the repository at this point in the history
  • Loading branch information
sugrado committed Apr 10, 2023
1 parent 4f97806 commit 1007492
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
9 changes: 9 additions & 0 deletions v1/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const {
} = require("./routes");
const events = require("./scripts/events");
const path = require("path");
const errorHandler = require("./middlewares/errorHandler");

config();
loaders();
Expand All @@ -28,4 +29,12 @@ app.listen(process.env.APP_PORT, () => {
app.use("/users", UserRoutes);
app.use("/sections", SectionRoutes);
app.use("/tasks", TaskRoutes);

app.use((req, res, next) => {
const error = new Error("Not found");
error.status = 404;
next(error);
});

app.use(errorHandler);
});
6 changes: 5 additions & 1 deletion v1/src/controllers/Projects.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const httpStatus = require("http-status");
const projectService = require("../services/ProjectService");
const ApiError = require("../errors/ApiError");

class ProjectsController {
index(req, res) {
Expand All @@ -25,7 +26,7 @@ class ProjectsController {
});
}

update(req, res) {
update(req, res, next) {
if (!req.params?.id)
return res
.status(httpStatus.NOT_FOUND)
Expand All @@ -34,6 +35,9 @@ class ProjectsController {
projectService
.update(req.body, req.params.id)
.then((updatedProject) => {
if (!updatedProject)
/*throw new ApiError("Project not found", 404);*/
return next(new ApiError("Project not found", 404));
res.status(httpStatus.OK).send(updatedProject);
})
.catch((e) => {
Expand Down
9 changes: 9 additions & 0 deletions v1/src/errors/ApiError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class ApiError extends Error {
constructor(message, status) {
super(message);
this.status = status;
this.message = message;
}
}

module.exports = ApiError;
8 changes: 8 additions & 0 deletions v1/src/middlewares/errorHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = (error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message || "Internal Server Error...",
},
});
};

0 comments on commit 1007492

Please sign in to comment.