From 8099a1470e70b9d3647f73f666afaaacda49c3a1 Mon Sep 17 00:00:00 2001 From: Louis-Marie Michelin <lmichelin@outlook.fr> Date: Tue, 8 Jun 2021 21:05:43 +0200 Subject: [PATCH] fix: improve error handler --- backend/server.js | 2 +- backend/services/jsonErrorHandler.js | 22 ++++++++-------------- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/backend/server.js b/backend/server.js index ded15b9..192d054 100644 --- a/backend/server.js +++ b/backend/server.js @@ -2,10 +2,10 @@ const express = require("express"); const logger = require("morgan"); const cors = require("cors"); const mongoose = require("mongoose"); -const jsonErrorHandler = require("./services/jsonErrorHandler"); const indexRouter = require("./routes/index"); const usersRouter = require("./routes/users"); const routeNotFoundJsonHandler = require("./services/routeNotFoundJsonHandler"); +const jsonErrorHandler = require("./services/jsonErrorHandler"); mongoose.connect(process.env.MONGO_DB_URL, { useNewUrlParser: true, diff --git a/backend/services/jsonErrorHandler.js b/backend/services/jsonErrorHandler.js index 0a379a2..0a69a05 100644 --- a/backend/services/jsonErrorHandler.js +++ b/backend/services/jsonErrorHandler.js @@ -1,22 +1,16 @@ // Custom error handler to send unhandled errors in JSON instead of HTML. // The error-handling middleware is a special type of Express 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) { - console.error(error); - if (res.headersSent) return next(error); - - if (process.env.NODE_ENV === "development") { - return res.status(500).json({ - message: error.toString(), - stackTrace: error.stack, - }); - } else { - // Hide error details in production to avoid security issues - return res.status(500).json({ - message: "Internal server error", - }); + if (!res.headersSent) { + if (process.env.NODE_ENV === "development") { + res.status(500).json({ message: error.toString() }); + } else { + // Hide error details in production to avoid security issues + res.status(500).json({ message: "Internal server error" }); + } } + next(error); }; module.exports = jsonErrorHandler; -- GitLab