Custom error objects in Javascript


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function ErrorConstructor(constructorName) {
  2. var errorConstructor = function(message, fileName, lineNumber) {
  3. // don't directly name this function, .name is used by Error.prototype.toString
  4. if (this == window) return new arguments.callee(message, fileName, lineNumber);
  5. this.name = errorConstructor.name;
  6. this.message = message||"";
  7. this.fileName = fileName||location.href;
  8. if (!isNaN(+lineNumber)) this.lineNumber = +lineNumber;
  9. else this.lineNumber = 1;
  10. }
  11. errorConstructor.name = constructorName||Error.prototype.name;
  12. errorConstructor.prototype.toString = Error.prototype.toString;
  13.  
  14. return errorConstructor;
  15. }
  16. Usage: ErrorConstructor([constructorName])
  17.  
  18. Note: If no constructorName is specified, the default of Error.prototype.name is used
  19.  
  20. Usage for generated error constructor: errorConstructor([message[, location[, lineNumber]])
  21.  
  22. Examples:
  23.  
  24. var SecurityError = ErrorConstructor("Security Error"),
  25. MarkupError = ErrorConstructor("(X)HTML Markup Error");
  26. //these will both throw a SecurityError starting with "Security Error on line 83:"
  27. var xss_error = "Possible XSS Vector\n\
  28. JSON XHR response parsed with eval()\n\
  29. Recommended fix: Parse JSON with JSON.parse";
  30. throw new SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
  31. throw SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
  32. //these will both throw the following MarkupError:
  33. //"(X)HTML Markup Error on line 1: Invalid DOCTYPE"
  34. throw new MarkupError("Invalid DOCTYPE");
  35. throw MarkupError("Invalid DOCTYPE");

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.