spee.ch/server/helpers/errorHandlers.js

46 lines
1.3 KiB
JavaScript
Raw Normal View History

2017-06-20 04:34:34 +02:00
const logger = require('winston');
2017-06-03 09:41:02 +02:00
module.exports = {
handleErrorResponse: function (originalUrl, ip, error, res) {
logger.error(`Error on ${originalUrl}`, module.exports.useObjectPropertiesIfNoKeys(error));
const [status, message] = module.exports.returnErrorMessageAndStatus(error);
res
.status(status)
.json(module.exports.createErrorResponsePayload(status, message));
},
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') {
status = 503;
2017-11-02 19:50:05 +01:00
message = 'Connection refused. The daemon may not be running.';
// fallback for everything else
} else {
2017-11-03 21:37:23 +01:00
status = 400;
if (error.message) {
message = error.message;
} else {
message = error;
};
};
2017-11-02 19:50:05 +01:00
return [status, message];
},
useObjectPropertiesIfNoKeys: function (err) {
if (Object.keys(err).length === 0) {
let newErrorObject = {};
Object.getOwnPropertyNames(err).forEach((key) => {
newErrorObject[key] = err[key];
});
return newErrorObject;
}
return err;
},
createErrorResponsePayload (status, message) {
return {
status,
success: false,
message,
};
},
};