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"?
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".
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...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With