UNPKG

@vara/custom-logic-sdk

Version:

Server Side JavaScript SDK for Custom Business Logic

70 lines (57 loc) 2.25 kB
/** * Created by stevenchin on 2/1/17. */ const appErrors = require('../constants/application-errors.json'); const _ = require('lodash'); // set of properties that should be added to the root of the error object and not the meta property const rootErrorProps = [ 'name', 'message', 'statusCode', 'code', 'details', 'innerError', ]; function addMetadataToErr(err, meta) { // add data properties specified if (_.isPlainObject(meta) && !_.isEmpty(meta)) { const errMetaProp = 'meta'; err[errMetaProp] = err[errMetaProp] || {}; const dataKeys = Object.keys(meta); dataKeys.forEach((key) => { if (rootErrorProps.indexOf(key) !== -1) { err[key] = meta[key]; } else { err[errMetaProp][key] = meta[key]; } }); if (_.isEmpty(err[errMetaProp])) { delete err[errMetaProp]; } } } /** * Creates an Application Error object by using the name parameter to get additional properties for the application error. * @param nameOrError {String|Error} - name of the application error; can be a new error or can map to an entry in the application-errors.json file * alternatively this can be an Error object that may be updated with a new message and/or custom properties. * @param [message=''] {String} - error message to display, overwrites the message property of any errors found in the application-errors.json file * @param [data] {Object} - additional properties to add to the error object; these will overwrite existing properties * @returns {Error} */ function customError(nameOrError, message = '', data = {}) { if (nameOrError instanceof Error) { nameOrError.message = message || nameOrError.message; addMetadataToErr(nameOrError, data); return nameOrError; } const defaultName = nameOrError || 'Error'; const err = new Error(message); err.name = _.get(appErrors, `${nameOrError}.name`, defaultName); // message property should be overridden when passed in err.message = message || _.get(appErrors, `${nameOrError}.message`, ''); err.code = _.get(appErrors, `${nameOrError}.code`, ''); err.statusCode = _.get(appErrors, `${nameOrError}.statusCode`, ''); addMetadataToErr(err, data); return err; } module.exports = customError;