Posted By


Sephr on 03/29/09

Tagged


Statistics


Viewed 644 times
Favorited by 1 user(s)

ErrorConstructor


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

ErrorConstructor produces error constructors that behave the same way as the seven native error constructors.

Usage: `ErrorConstructor([constructorName])`

*If no constructorName is specified, the default of `Error.prototype.name` is used*

Usage for generated error constructor: `errorConstructor([message[, location[, lineNumber]])`

Examples:

var SecurityError = ErrorConstructor("Security Error"),
MarkupError = ErrorConstructor("(X)HTML Markup Error");
//these will both throw a SecurityError starting with "Security Error on line 83:"
var xss_error = "Possible XSS Vector\n\
JSON XHR response parsed with eval()\n\
Recommended fix: Parse JSON with JSON.parse";
throw new SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
throw SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
//these will both throw the following MarkupError:
//"(X)HTML Markup Error on line 1: Invalid DOCTYPE"
throw new MarkupError("Invalid DOCTYPE");
throw MarkupError("Invalid DOCTYPE");


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.  
  17. // This part is optional and simulates an Error object for Object.prototype.toString
  18. (function(){
  19. var realObjectToString = Object.prototype.toString,
  20. realFunctionToString = Function.prototype.toString;
  21.  
  22. Object.prototype.toString = function() {
  23. if (this.constructor.prototype.toString === Error.prototype.toString)
  24. return "[object Error]";
  25. else
  26. return realObjectToString.call(this);
  27. };
  28.  
  29. Function.prototype.toString = function() {
  30. if (this === Function.prototype.toString
  31. || this === Object.prototype.toString)
  32. return realObjectToString.toString();
  33. else
  34. return realFunctionToString.call(this);
  35. }
  36. })()

URL: http://eligrey.com/2009/03/29/custom-error-constructors/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.