2018-12-27 11:54:16 +00:00
|
|
|
const UserError = require('../../util/user-error');
|
2019-06-11 13:46:42 +00:00
|
|
|
const logToConsole = require('strong-error-handler/lib/logger');
|
2018-01-29 18:57:00 +00:00
|
|
|
|
2018-01-29 11:37:54 +00:00
|
|
|
module.exports = function() {
|
|
|
|
return function(err, req, res, next) {
|
2018-01-29 18:57:00 +00:00
|
|
|
// Thrown user errors
|
|
|
|
if (err instanceof UserError) {
|
2018-11-20 09:34:29 +00:00
|
|
|
err.message = req.__(err.message, ...err.translateArgs);
|
2018-01-29 18:57:00 +00:00
|
|
|
return next(err);
|
2018-01-29 11:37:54 +00:00
|
|
|
}
|
2018-01-29 18:57:00 +00:00
|
|
|
|
|
|
|
// Validation errors
|
|
|
|
if (err.statusCode == 422) {
|
|
|
|
try {
|
|
|
|
let code;
|
|
|
|
let messages = err.details.messages;
|
|
|
|
for (code in messages) break;
|
|
|
|
err.message = req.__(messages[code][0]);
|
|
|
|
return next(err);
|
|
|
|
} catch (e) {}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MySQL user-defined exceptions
|
|
|
|
if (err.sqlState == '45000')
|
|
|
|
return next(new UserError(req.__(err.sqlMessage)));
|
|
|
|
|
2019-06-27 10:48:47 +00:00
|
|
|
// Logs error to console
|
|
|
|
|
|
|
|
let env = process.env.NODE_ENV;
|
|
|
|
let useCustomLogging = env && env != 'development' &&
|
|
|
|
(!err.statusCode || err.statusCode >= 500);
|
|
|
|
|
|
|
|
if (useCustomLogging)
|
2019-06-11 13:46:42 +00:00
|
|
|
logToConsole(req, err);
|
|
|
|
|
2018-01-29 11:37:54 +00:00
|
|
|
next(err);
|
|
|
|
};
|
|
|
|
};
|