Throw exceptions with line number in JavaScript

There might be some scenarios that we need to throw exceptions in JavaScript, and get the line number, and the call stack, specially when we are developing a feature that will be used by other developers. Since JavaScript have far less tools to aid in debugging than other languages, when we are building a functionality it is handy to throw an exception when the developer that is using you code need to meet certain requirements to let them know when have been a violation in the code in the logic.

throw exceptions

This is widely used when we use the network to do the communication and transmit the data with the back-end, and the connection fails and we want to show specifically where in the code the error happened (code line). Especially when the component you are developing takes thousand of code lines. Or when we want to force the consumed of our component to specify a specific type of object. Let’s see the following example.

Throw exceptions example:

function someFunction(callback){
    if(typeof callback != ‘function’){
        // throw an exception here
    }else{
        callback();
    }
}

 

javascript book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

With this code we can achieve it:

var err;
try {
throw new Error('myError');
} catch (e) {
err = e;
}
if (!!err)
console.log(err.stack);

if you put this code in the console (chrome) this is the result:

Error: myError.
at :4:11
at Object.InjectedScript._evaluateOn (:777:140).
at Object.InjectedScript._evaluateAndWrap (:710:34).
at Object.InjectedScript.evaluate (:626:21).

This is the code wrapped in a function to enable re-utilization:

Compatibility by Mozilla.

Descktop compatibility:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) 10 (Yes) 6

 

Mobile compatibility:

Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support Android 4 (perhaps Android 3, but not Android 2) ? ? ? ? 6