Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript try/catch: errors or exceptions?

OK. I may be splitting hairs here, but my code isn't consistent and I'd like to make it so. But before I do, I want to make sure I'm going the right way. In practice this doesn't matter, but this has been bothering me for a while so I figured I'd ask my peers...

Every time I use a try... catch statement, in the catch block I always log a message to my internal console. However my log messages are not consistent. They either look like:

catch(err) {
DFTools.console.log("someMethod caught an error: ",err.message);
...

or:

catch(ex) {
DFTools.console.log("someMethod caught an exception: ",ex.message);
...

Obviously the code functions properly either way but it's starting to bother me that I sometimes refer to "errors" and sometimes to "exceptions". Like I said, maybe I'm splitting hairs but which is the proper terminology? "Exception", or "Error"?

like image 915
Josh Avatar asked Apr 06 '10 18:04

Josh


2 Answers

This is a bit subjective, but to me an error is when someone or something does something wrong, improper, or invalid. It could be a syntax error, a logical error, a read error, user error, or even a social error. It's an abstract concept.

An exception, on the other hand, is an object that is created and thrown when a certain condition occurs in code. It may or may not correspond to a conceptual error. So to me, the proper nomenclature is "exception".

like image 74
tloflin Avatar answered Sep 30 '22 20:09

tloflin


The ECMAScript specification calls them exceptions. You might want to do likewise.

To make your logging more informative:

catch(ex) {
    DFTools.console.log("someMethod caught an exception of type " 
       + ex.name + ": ", ex.message);

You might also want to bear in mind that exceptions (unfortunately) can be of any type, and so don't necessarily have name and message properties:

catch(ex) {
    if (ex.message && ex.name) {        
        DFTools.console.log("someMethod caught an exception of type " 
           + ex.name + ": ", ex.message);
    } else /* deal with it somehow */

As this is starting to look pretty cumbersome to repeat everywhere, you might want to capture it in a function:

function logExceptions(methodName, action) {

    try {

        action();

    } catch (ex) {
        if (ex.message && ex.name) {        
            DFTools.console.log("someMethod caught an exception of type " 
               + ex.name + ": ", ex.message);
        } else {
            DFTools.console.log("someMethod caught a poorly-typed exception: " + ex);
        }
    }
}

Now you can say:

logExceptions(function() {

    // do some risky stuff...

});
like image 35
Daniel Earwicker Avatar answered Sep 30 '22 18:09

Daniel Earwicker