Node.js Best Practice Exception Handling

后端 未结 10 1457
遥遥无期
遥遥无期 2020-11-22 04:19

I just started trying out node.js a few days ago. I\'ve realized that the Node is terminated whenever I have an unhandled exception in my program. This is different than the

10条回答
  •  忘了有多久
    2020-11-22 04:57

    One instance where using a try-catch might be appropriate is when using a forEach loop. It is synchronous but at the same time you cannot just use a return statement in the inner scope. Instead a try and catch approach can be used to return an Error object in the appropriate scope. Consider:

    function processArray() {
        try { 
           [1, 2, 3].forEach(function() { throw new Error('exception'); }); 
        } catch (e) { 
           return e; 
        }
    }
    

    It is a combination of the approaches described by @balupton above.

提交回复
热议问题