2018-08-31 15:04:04 +00:00
|
|
|
// import { inspect } from 'util';
|
|
|
|
// import _ from 'lodash/fp';
|
2015-08-04 08:25:34 +00:00
|
|
|
import accepts from 'accepts';
|
2018-08-29 19:52:41 +00:00
|
|
|
|
2018-08-31 15:04:04 +00:00
|
|
|
import { homeLocation } from '../../../config/env';
|
2018-08-29 19:52:41 +00:00
|
|
|
|
2017-07-13 18:39:07 +00:00
|
|
|
import { unwrapHandledError } from '../utils/create-handled-error.js';
|
2015-08-04 08:25:34 +00:00
|
|
|
|
2017-12-28 00:41:42 +00:00
|
|
|
const isDev = process.env.NODE_ENV !== 'production';
|
|
|
|
|
|
|
|
export default function prodErrorHandler() {
|
2015-08-04 08:25:34 +00:00
|
|
|
// error handling in production.
|
2018-11-29 12:12:15 +00:00
|
|
|
// eslint-disable-next-line no-unused-vars
|
2018-08-31 15:04:04 +00:00
|
|
|
return function(err, req, res, next) {
|
2017-12-28 19:19:31 +00:00
|
|
|
const handled = unwrapHandledError(err);
|
|
|
|
// respect handled error status
|
|
|
|
let status = handled.status || err.status || res.statusCode;
|
|
|
|
if (!handled.status && status < 400) {
|
|
|
|
status = 500;
|
2015-08-04 08:25:34 +00:00
|
|
|
}
|
2017-12-28 19:19:31 +00:00
|
|
|
res.status(status);
|
2015-08-04 08:25:34 +00:00
|
|
|
|
|
|
|
// parse res type
|
2016-07-16 17:40:14 +00:00
|
|
|
const accept = accepts(req);
|
|
|
|
const type = accept.type('html', 'json', 'text');
|
2015-08-04 08:25:34 +00:00
|
|
|
|
2018-08-29 19:52:41 +00:00
|
|
|
const redirectTo = handled.redirectTo || `${homeLocation}/`;
|
2018-08-31 15:04:04 +00:00
|
|
|
const message =
|
|
|
|
handled.message || 'Oops! Something went wrong. Please try again later';
|
2017-12-28 00:41:42 +00:00
|
|
|
|
2017-12-28 01:34:56 +00:00
|
|
|
if (isDev) {
|
|
|
|
console.error(err);
|
|
|
|
}
|
|
|
|
|
2015-08-04 08:25:34 +00:00
|
|
|
if (type === 'html') {
|
2015-08-16 22:26:43 +00:00
|
|
|
if (typeof req.flash === 'function') {
|
2018-01-12 22:16:33 +00:00
|
|
|
req.flash(handled.type || 'danger', message);
|
2015-08-16 22:26:43 +00:00
|
|
|
}
|
2018-08-30 14:27:53 +00:00
|
|
|
return res.redirectWithFlash(redirectTo);
|
2015-08-04 08:25:34 +00:00
|
|
|
// json
|
|
|
|
} else if (type === 'json') {
|
|
|
|
res.setHeader('Content-Type', 'application/json');
|
|
|
|
return res.send({
|
2018-01-01 23:39:14 +00:00
|
|
|
type: handled.type || 'errors',
|
2017-07-13 18:39:07 +00:00
|
|
|
message
|
2015-08-04 08:25:34 +00:00
|
|
|
});
|
|
|
|
// plain text
|
|
|
|
} else {
|
|
|
|
res.setHeader('Content-Type', 'text/plain');
|
|
|
|
return res.send(message);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|