Domains not properly catching errors while testing nodeJS in mocha

前端 未结 2 896
暗喜
暗喜 2021-01-01 05:21

When running tests that utilize domains for error handling, Mocha still appears to be throwing an error even if a domain handler inside a library should have caught the erro

2条回答
  •  盖世英雄少女心
    2021-01-01 05:54

    Found the problem. NodeJS domains catch synchronous errors but the event continues to bubble to a try/catch. If you wrap a domain.run() in a try/catch then the domain error handler AND the catch will be executed.

    Thus, it seems the best practice is to use process.nextTick inside all domain.run(). This is shown in the docs example, but isn't expressed as explicitly as I would prefer.

    Example:

    d.run(function() {
        process.nextTick(function() {
            // do stuff
        });
    });
    

    In this case, the flaw is not in Mocha.

    Proof of NodeJS domains not catching synchronous errors in try/catch: https://gist.github.com/owenallenaz/7141699

提交回复
热议问题