Skip to content
Snippets Groups Projects
Commit 8099a147 authored by Louis-Marie Michelin's avatar Louis-Marie Michelin
Browse files

fix: improve error handler

parent 6f1f5ee3
Branches
No related tags found
No related merge requests found
...@@ -2,10 +2,10 @@ const express = require("express"); ...@@ -2,10 +2,10 @@ const express = require("express");
const logger = require("morgan"); const logger = require("morgan");
const cors = require("cors"); const cors = require("cors");
const mongoose = require("mongoose"); const mongoose = require("mongoose");
const jsonErrorHandler = require("./services/jsonErrorHandler");
const indexRouter = require("./routes/index"); const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users"); const usersRouter = require("./routes/users");
const routeNotFoundJsonHandler = require("./services/routeNotFoundJsonHandler"); const routeNotFoundJsonHandler = require("./services/routeNotFoundJsonHandler");
const jsonErrorHandler = require("./services/jsonErrorHandler");
mongoose.connect(process.env.MONGO_DB_URL, { mongoose.connect(process.env.MONGO_DB_URL, {
useNewUrlParser: true, useNewUrlParser: true,
......
// Custom error handler to send unhandled errors in JSON instead of HTML. // Custom error handler to send unhandled errors in JSON instead of HTML.
// The error-handling middleware is a special type of Express middleware // The error-handling middleware is a special type of Express middleware
// that needs to have four arguments as opposed to a regular middleware. // that needs to have four arguments as opposed to a regular middleware.
// eslint-disable-next-line no-unused-vars
const jsonErrorHandler = function (error, req, res, next) { const jsonErrorHandler = function (error, req, res, next) {
console.error(error); if (!res.headersSent) {
if (res.headersSent) return next(error);
if (process.env.NODE_ENV === "development") { if (process.env.NODE_ENV === "development") {
return res.status(500).json({ res.status(500).json({ message: error.toString() });
message: error.toString(),
stackTrace: error.stack,
});
} else { } else {
// Hide error details in production to avoid security issues // Hide error details in production to avoid security issues
return res.status(500).json({ res.status(500).json({ message: "Internal server error" });
message: "Internal server error", }
});
} }
next(error);
}; };
module.exports = jsonErrorHandler; module.exports = jsonErrorHandler;
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment