From 003861d2fdb37b83e1d0939d49b70fbc67766997 Mon Sep 17 00:00:00 2001 From: Ken Sheedlo Date: Fri, 7 Jun 2013 18:24:30 -0700 Subject: chore(minErr): replace ngError with minErr --- src/minErr.js | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/minErr.js (limited to 'src/minErr.js') diff --git a/src/minErr.js b/src/minErr.js new file mode 100644 index 00000000..b6c447ca --- /dev/null +++ b/src/minErr.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * @description + * + * This object provides a utility for producing rich Error messages within + * Angular. It can be called as follows: + * + * var exampleMinErr = minErr('example'); + * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); + * + * The above creates an instance of minErr in the example namespace. The + * resulting error will have a namespaced error code of example.one. The + * resulting error will replace {0} with the value of foo, and {1} with the + * value of bar. The object is not restricted in the number of arguments it can + * take. + * + * If fewer arguments are specified than necessary for interpolation, the extra + * interpolation markers will be preserved in the final string. + * + * Since data will be parsed statically during a build step, some restrictions + * are applied with respect to how minErr instances are created and called. + * Instances should have names of the form namespaceMinErr for a minErr created + * using minErr('namespace') . Error codes, namespaces and template strings + * should all be static strings, not variables or general expressions. + * + * @param {string} module The namespace to use for the new minErr instance. + * @returns {function(string, string, ...): Error} instance + */ + +function minErr(module) { + return function () { + var prefix = '[' + (module ? module + ':' : '') + arguments[0] + '] ', + template = arguments[1], + templateArgs = arguments, + message; + + message = prefix + template.replace(/\{\d+\}/g, function (match) { + var index = +match.slice(1, -1), arg; + + if (index + 2 < templateArgs.length) { + arg = templateArgs[index + 2]; + if (isFunction(arg)) { + return arg.toString().replace(/ \{[\s\S]*$/, ''); + } else if (isUndefined(arg)) { + return 'undefined'; + } else if (!isString(arg)) { + return toJson(arg); + } + return arg; + } + return match; + }); + + return new Error(message); + }; +} -- cgit v1.2.3