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
No related branches found
No related tags found
No related merge requests found
......@@ -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,
......
// 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 (!res.headersSent) {
if (process.env.NODE_ENV === "development") {
return res.status(500).json({
message: error.toString(),
stackTrace: error.stack,
});
res.status(500).json({ message: error.toString() });
} else {
// Hide error details in production to avoid security issues
return res.status(500).json({
message: "Internal server error",
});
res.status(500).json({ message: "Internal server error" });
}
}
next(error);
};
module.exports = jsonErrorHandler;
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment