'use strict'; const _ = require('lodash'); const httpStatus = require('http-status'); //////////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS //////////////////////////////////////////////////////////////////////////////// function buildErrorLog(err) { let errorLog; if (_.isUndefined(err)) { errorLog = 'Error not defined'; } else if (!_.isUndefined(err.message)) { errorLog = err.message; } else if (!_.isUndefined(err.stack)) { errorLog = err.stack; } else { errorLog = JSON.stringify(err); } return errorLog; } function buildErrorResponse(nameController, nameMethod, error) { const errorDescription = buildErrorLog(error); const jsonResultFailed = { code: httpStatus.INTERNAL_SERVER_ERROR, message: 'Internal Server Error', description: `Internal Application Error in ${nameController}:${nameMethod}. ${errorDescription}` } return jsonResultFailed; } //////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS //////////////////////////////////////////////////////////////////////////////// function handleErrorResponse(controllerName, methodName, error, res) { const jsonResultFailed = buildErrorResponse(controllerName, methodName, error); res.status(httpStatus.INTERNAL_SERVER_ERROR).send(jsonResultFailed); } //////////////////////////////////////////////////////////////////////////////// // MODULE EXPORTS //////////////////////////////////////////////////////////////////////////////// module.exports = { handleErrorResponse, // for testing buildErrorLog, buildErrorResponse };