dracoblue.net

JavaScript new Exception(name,message)

Today I noticed that JavaScript doesn't provide an easy way to make/raise custom exceptions? while still providing an useful stacktrace.

Here is a code snippet used for the

GTA:T JavaScript interface to find the fitting stacktrace for a custom JavaScript Exception.

function Exception(name,msg) {
    try {
        throw new Error("")
    } catch (e) {
        e.stack = e.stack.split("@"+e.fileName+":").join(":");
        full_stack = e.stack.split("\\n");
        stack = [];
        stack[0] = "Exception: "+name+"(\""+msg+"\")"
        for (var i=2;i<full_stack.length-3;i++) {
            entry = full_stack[i];
            entry_detailed = entry.split(":");
            entry_detailed[1] = entry_detailed[1] - 4; // THIS is to
            // mark, that we'll "move" the source 4 lines higher,
            // ... because it's eval code executed. Remove that for
            // clear values.
            if (i==2) lineNumber = entry_detailed[1];
            stack[i] = entry_detailed.join(":");
        }
        return {
            name:name,
            message:msg,
            stack:stack.join("\\n"),
            lineNumber:lineNumber
        };
    }
}

You may use it that way:

try {
    function a() {
        throw new Exception("MyException","No permission!")
    }
    function b() {
        a()
    }
    b()
} catch (e) {
    alert(e.name+": "+e.message);
}
// Tested in Firefox
/* e:
Object {
  [name] => MyException
  [message] => No permission!
  [stack] => Exception: MyException("No permission!")
             a():3
             b():6
             execute():10
  [lineNumber] => 3
}*/
In html, javascript, open source by
@ 05 Jun 2008, Comments at Reddit & Hackernews

Give something back

Were my blog posts useful to you? If you want to give back, support one of these charities, too!

Report hate in social media Campact e.V. With our technology and your help, we protect the oceans from plastic waste. Gesellschaft fur Freiheitsrechte e. V. The civil eye in the mediterranean

Recent Dev-Articles

Read recently

Recent Files

About