Centralized exception handling in Node.JS. Part 2



    Four months ago, I wrote about how you can conveniently catch exceptions in node.js, including asynchronous ones, that is, those that are thrown by code that is triggered by an event loop. In that article, I used the control-block module to deal with them, since the standard try-catch block could not cope.

    As it turned out, around the same time, Adam Crabtree released a stable version of a control-block-like module called trycatch .

    The trycatch module provides some additional features that are not in the control-block:

    1. Eliminates the need to additionally wrap callbacks passed to setTimeout, etc.

    To do this, the trycatch module replaces the setTimeout, setInterval, fs module functions at boot, so that there is no need for constant calls to Block.guard () when sending callbacks. This is done automatically.

    2. As a result, trycatch provides support for third-party libraries.

    Due to the need to wrap callbacks, control-block could not catch some asynchronous exceptions that occurred in third-party libraries.

    Suppose we have such an unreasonable third-party library that is too tough even for the control-block module:
    function blackBox() {
      setTimeout(function() {
        throw new Error('black box error');
      }, 10);
    }
    

    And this is the code that thanks to trycatch now knows how to work safely with it:
    var trycatch = require('trycatch');
    trycatch(function() {
      setInterval(blackBox, 1000);
    }, function(err) {
      console.log('caught!');
      console.log(err.stack);
    });
    

    He will output:


    3. Long stack traces

    Thanks to integration with the long-stack-traces module, the trycatch module can help with debugging if you ask it to output long stack traces that correctly track asynchronous exceptions:
    var trycatch = require('trycatch');
    trycatch.configure({'long-stack-traces': true});
    trycatch(function() {
      setInterval(blackBox, 1000);
    }, function(err) {
      console.log('caught!');
      console.log(err.stack);
    });
    

    This code will already output such a stack:


    By the way, until recently, trycatch pre-compilation of a long stack trace was mandatory, which compared to control-block gave a performance of about 70-100 times lower. I discussed this problem with the author, suggested a possible solution, and yesterday he released a new version , which is now based on the control-block module, which gives a high speed module. At the same time, the opportunity is left to enable long stack traces when necessary, for example, on a server where development is underway, and speed is not critical. It turned out a kind of symbiosis, which took only the best from both projects.

    So despite the fact that the trycatch module is not quite perfect even in my opinionI believe this is the best solution to handle asynchronous exceptions.

    Also popular now: