Eli Grey

Custom error constructors

Most of the time, the standard six native error constructors and the one generic error constructor are not specific enough for an error. What if you want your library to throw a custom SecurityError if it detects an XSS vector on a website? I made a function to create such constructors that behave the exact same way the native error constructors, like SyntaxError by using methods like Error.prototype.toString and the standard error object format. This code makes throwing a custom fake error constructor made with ErrorConstructor("SyntaxError") have the same output as a native SyntaxError in a JavaScript shell. I’ve tested the code in Firefox 3/3.5 and Opera 9.6 and it seems to work fine. Comment and say if it works in your browser too.

function ErrorConstructor(constructorName) {
  var errorConstructor = function(message, fileName, lineNumber) {
  // don't directly name this function, .name is used by Error.prototype.toString
    if (this == window) return new arguments.callee(message, fileName, lineNumber);
    this.name = errorConstructor.name;
    this.message = message||"";
    this.fileName = fileName||location.href;
    if (!isNaN(+lineNumber)) this.lineNumber = +lineNumber;
    else this.lineNumber = 1;
  }
  errorConstructor.name = constructorName||Error.prototype.name;
  errorConstructor.prototype.toString = Error.prototype.toString;
 
  return errorConstructor;
}

Usage: ErrorConstructor([constructorName])
Note: 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 Vectorn
 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");