EML
EML

Reputation: 10280

JavaScript contracts and assertions

This has bugged me for a while. I throw an exception on an assertion failure, but this is only helpful if I can actually catch the exception (in which case I alert the user). If I can't catch the exception, then

  1. I'm relying on the browser to notify the user that there's been an internal error (the browser may do nothing, so the user never finds out that there's a problem), and
  2. I don't get a look-in, and so can't clean up.

So, is there actually a good way to handle assertion errors in JavaScript? Is there some way to catch uncaught exceptions? Note that I'm not interested in unit testing, user errors, and so on - I'm only concerned with contract programming, where both the user and developer need to know that there has been an error.

Upvotes: 3

Views: 221

Answers (1)

Bergi
Bergi

Reputation: 665574

For assertions, there is console.assert(). But that will only log the message and go on.

With HTML5 it is also possible to catch unhandled exceptions using the window.onerror handler. There's an excellent article on dev.opera how this can be used to show fancy error messages to the user and even log exceptions to the server.

If you can't use that, you're left with wrapping try-catch-clauses around everything (especially "execution entry points" like event handlers, timeouts and co.). Or you could handle the errors before throwing them:

function SmartError(message) {
    Error.call(this, message);
    $('<div class="error">Some problem occured, the app will stop working</div>')
        .appendTo("body");
    $.post("/log/clientside/js.php", this);
    ...
}

if (something.does(! "work"))
    throw new SmartError("mysterious problem");

Upvotes: 2

Related Questions