Skip to content

Instantly share code, notes, and snippets.

@bigmeech
Created November 4, 2016 13:32
Show Gist options
  • Select an option

  • Save bigmeech/cb9d2f52fc5ffd3467030c031e71de41 to your computer and use it in GitHub Desktop.

Select an option

Save bigmeech/cb9d2f52fc5ffd3467030c031e71de41 to your computer and use it in GitHub Desktop.
'use strict';
const _ = require('lodash');
const errors = [
{
code: 404,
httpStatus: 404,
errorTemplate: '${resourceName} resource not found'
},
{
code: 11000,
httpStatus: 409,
errorTemplate: '${resourceName} already exists'
},
{
code: 500,
httpStatus: 500,
errorTemplate: 'Oops! Something went wrong'
}
];
/**
* complies template string with placeholder
* @param stringWithPlaceholder
* @param context
*/
function compileTemplate (stringWithPlaceholder, context, options) {
if (options) {
_.templateSettings(options);
}
return _.template(stringWithPlaceholder)(context);
}
/**
* Main error helper constructor
* @constructor
*/
function ErrorHelper () {}
/**
* finds error by code and compiles the final message using placeholder
* @param code
* @param msgPlaceholder
* @returns {null}
*/
ErrorHelper.prototype.findByCode = function findErrorByCode (code, msgPlaceholder) {
const error = _.find(errors, { code: code });
if (!error) {
return null;
}
let derivedError = new Error();
derivedError.message = compileTemplate(error.errorTemplate, msgPlaceholder);
derivedError.status = error.httpStatus;
derivedError.code = error.code;
return derivedError;
};
module.exports = new ErrorHelper();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment