javascript - How do I handle an exception thrown for an undefined function? -
in infamous validation directive, below, pass name of required validation function parameter attribute based directive:
mybigapp.directive("mlngvalidations", function ($compile) { var valattributes = { phonenumber: function (element) { element.attr("ng-pattern", "/^[0-9]+$/"); element.attr("ng-minlength", 5); element.attr("ng-maxlength", 8); } } return { priority: 10000, terminal: true, link: function (scope, element, attrs) { var validationtype = attrs.mlngvalidations; valattributes[validationtype](element); element.removeattr("ml-ng-validations"); $compile(element)(scope); } }; });
if declare element mispelled validation function, e.g:
<input type="text" class="form-control" ml-ng-validations="phoonenumber" />
i non unexpected exception:
typeerror: valattributes[validationtype] not function
i more informative message @ least, preferable without having define new exception, maybe like:
typeerror: validation function phoonenumber not defined
how can achieve this?
in case, appear own code calling non-function: don't. ounce of prevention worth pound of cure.
mybigapp.directive("mlngvalidations", function ($compile) { var valattributes = { phonenumber: function (element) { element.attr("ng-pattern", "/^[0-9]+$/"); element.attr("ng-minlength", 5); element.attr("ng-maxlength", 8); } } return { priority: 10000, terminal: true, link: function (scope, element, attrs) { var validationtype = attrs.mlngvalidations; var fn = valattributes[validationtype]; if (typeof fn !== "function") { throw new error("validation function " + validationtype + " not defined"); } fn(element); element.removeattr("ml-ng-validations"); $compile(element)(scope); } }; });
if don't own calling code, can use regular try .. catch
if own code encloses calling code. this, seems unlikely, , you're stuck ugly, browser-specific hacks firefox's window.onerror. @ least let catch exception , examine it, possibly re-throwing own, more descriptive error. doesn't seem worth effort me.
Comments
Post a Comment