spee.ch/helpers/errorHandlers.js

69 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-06-20 04:34:34 +02:00
const logger = require('winston');
2017-08-03 02:13:02 +02:00
const { postToStats } = require('../controllers/statsController.js');
2017-06-20 04:34:34 +02:00
2017-06-03 09:41:02 +02:00
module.exports = {
2017-11-02 19:50:05 +01:00
returnErrorMessageAndStatus: function (error) {
2017-11-03 21:37:23 +01:00
let status, message;
// check for daemon being turned off
if (error.code === 'ECONNREFUSED') {
2017-11-02 19:50:05 +01:00
status = 503;
message = 'Connection refused. The daemon may not be running.';
2017-11-03 21:37:23 +01:00
// check for errors from the deamon
} else if (error.response) {
2017-11-02 19:50:05 +01:00
status = error.response.status || 500;
if (error.response.data) {
if (error.response.data.message) {
2017-11-02 19:50:05 +01:00
message = error.response.data.message;
} else if (error.response.data.error) {
2017-11-02 19:50:05 +01:00
message = error.response.data.error.message;
} else {
message = error.response.data;
}
2017-11-02 19:50:05 +01:00
} else {
message = error.response;
}
2017-11-03 21:37:23 +01:00
// check for spee.ch thrown errors
} else if (error.message) {
status = 400;
message = error.message;
// fallback for everything else
} else {
2017-11-03 21:37:23 +01:00
status = 400;
2017-11-02 19:50:05 +01:00
message = error;
}
2017-11-02 19:50:05 +01:00
return [status, message];
},
handleRequestError: function (action, originalUrl, ip, error, res) {
logger.error(`Request Error on ${originalUrl}`, module.exports.useObjectPropertiesIfNoKeys(error));
postToStats(action, originalUrl, ip, null, null, error);
const errorStatusAndMessage = this.returnErrorMessageAndStatus(error);
res
.status(errorStatusAndMessage[0])
.render('requestError', {
status : errorStatusAndMessage[0],
message: errorStatusAndMessage[1],
});
},
handleApiError: function (action, originalUrl, ip, error, res) {
logger.error(`Api ${action} Error on ${originalUrl}`, module.exports.useObjectPropertiesIfNoKeys(error));
postToStats(action, originalUrl, ip, null, null, error);
const errorStatusAndMessage = this.returnErrorMessageAndStatus(error);
res
.status(errorStatusAndMessage[0])
.json({
success: false,
message: errorStatusAndMessage[1],
});
},
2017-11-02 19:50:05 +01:00
useObjectPropertiesIfNoKeys: function (err) {
if (Object.keys(err).length === 0) {
let newErrorObject = {};
Object.getOwnPropertyNames(err).forEach((key) => {
newErrorObject[key] = err[key];
});
return newErrorObject;
}
return err;
},
};