Skip to content

Instantly share code, notes, and snippets.

@logicplace
Created November 6, 2011 09:52
Show Gist options
  • Save logicplace/1342706 to your computer and use it in GitHub Desktop.
Save logicplace/1342706 to your computer and use it in GitHub Desktop.
Easiest, proper custom error in JavaScript
//Ensure report
console = typeof(console)=="undefined"?{log:alert}:console;
//Quick diff function
function diffContents(c){
return "(([\\s\\S]*?)("+(c
.replace(/\\/,"\\\\")
.replace(/([\[\]{}()^$+*.?|])/,"\\$1")
)+"?))?";
}
function diff(a,b){
a = a || ""; b = b || "";
var df = b.match(new RegExp("^"+a.replace(/([\s\S])/g,diffContents)+"(([\\s\\S]*)($))")),
ret = [], lastWasDiff=false;
for(var i=1, j=0, len=df.length; i < len; i+=3, ++j){
//i: whole, i+1: difference, i+2: similarity
if(df[i+1]){
var atxt = df[i+2]?"":a.charAt(j);
if(lastWasDiff){
ret[ret.length-1].atxt += atxt;
ret[ret.length-1].btxt += df[i+1];
} else {
ret.push({
"pos": j, "atxt": atxt, "btxt": df[i+1]
});
lastWasDiff=true;
}
} else lastWasDiff=false;
}
return ret;
}
//Define error class
function TestError(x){
this.__proto__.__proto__ = (new Error(this.message = x));
this.name = this.constructor.name;
if("stack" in this)this.stack = this.stack.replace("Error",this.name);
}
//Perform tests
var e = new TestError("<MESSAGE>"),stackDiff;
console.log(
(e instanceof TestError?"Passed":"Failed")+": instanceof TestError",
(e instanceof Error?"\nPassed":"\nFailed")+": instanceof Error"
);
if("stack" in e){
console.log((e.stack.indexOf("<MESSAGE>")!=-1?"Passed":"Failed")+": finding message");
console.log((e.stack.indexOf("TestError",e.stack.indexOf("TestError")+1)!=-1?
"Passed":"Failed")+": finding own name"
);
if((stackDiff=diff(e.stack,(new TestError("<MESSAGE>")).stack)).length){
console.log(stackDiff);
} else {
console.log("Failed: stack trace is the same");
}
} else {
console.log("No stack traces in this JS implementation.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment