Skip to content

Commit

Permalink
error and not found handlers amendments and fix
Browse files Browse the repository at this point in the history
  • Loading branch information
borisding committed Jul 1, 2021
1 parent eb0be89 commit 0c5c608
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 29 deletions.
34 changes: 11 additions & 23 deletions server/middleware/errorHandler.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,17 @@
const logger = require('../logger');
const { isDev } = require('../../utils');

// custom error handler for the app/api
// only include error stack in development mode
const errorHandler =
({ json = false } = {}) =>
// eslint-disable-next-line no-unused-vars
(err, req, res, next) => {
const code = err.statusCode || 500;
const stack = isDev ? err.stack : null;
const error = isDev ? err.message : 'Sorry! Something went wrong.';
const errorData = { code, error, stack };
// custom error handler
// eslint-disable-next-line no-unused-vars
const errorHandler = () => (err, req, res, next) => {
const code = err.statusCode || 500;
const name = err.name || 'Error';
const message = err.message || 'Sorry! Something went wrong.';
const errorData = { name, code, message };

res.status(code);
// logs error stack
logger.error(err.stack);

// logs error stack
logger.error(err.stack);

// giving erros in JSON format if request made via Ajax or `json` key is true
// otherwise, rendering 500 template with passed params
if (req.xhr || !!json) {
res.json(errorData);
} else {
res.send('500 Internal Server Error.');
}
};
res.status(code).json(errorData);
};

module.exports = errorHandler;
11 changes: 5 additions & 6 deletions server/middleware/notFoundHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@

const code = 404;
const notFoundHandler = () => (req, res) => {
res.status(code);
res.format({
res.status(code).format({
json() {
res.send({ code, message: 'Resource not found.' });
},
html() {
res.render(`${code}`, { code, message: 'Page not found.' });
res.send({
code,
message: 'Resource not found.'
});
}
});
};
Expand Down

0 comments on commit 0c5c608

Please sign in to comment.