ciplogic.com
Live with grace. Write superb software.

Many times in JavaScript, I like to log errors in case exceptions happen, that output what exactly went wrong, without actually taking action.

For example:

1
2
3
4
5
6
try {
  callPotentialDangerousStuff();
} catch (e) {
  console.error("dangerous stuff is not working :(");
  throw e;
}

This has the side effect of loosing the stack trace if I break on "uncaught exceptions", and breaking on "all exceptions" is absolutely no option, since many frameworks use the exception handling as mechanisms of detecting various features of the browser environment.

Thus I came up with this pattern:

1
2
3
4
5
6
7
8
9
10
var executionSuccessful = false;
 
try {
  callPotentialDangerousStuff();
  executionSuccessful = true;
} finally {
  if (!executionSuccessful) {
    console.error("dangerous stuff is not working :(");
  }
}

So if an exception happens, I can still break on all exceptions, but also get my log right.

Can you imagine how cool it would be to chain exceptions like in Java? For example:

1
2
3
4
5
6
try {
  callPotentialDangerousStuff();
} catch (e) {
  console.error("dangerous stuff is not working :(");
  throw new Error("dangerous stuff", e);
}

At least we can dream about it, and appreciate more languages that do offer chaining of exceptions.

Disqus Comments

comments powered by Disqus

Germanium

The one to rule them all. The browsers that is.

SharpKnight

SharpKnight is an Android chess game.

MagicGroup

MagicGroup is an eclipse plugin.