浅聊 nodejs 的错误处理

44 阅读1分钟

throw Error objects(抛出Error构造函数)

JS 中,可以 throw 任何值,但在 node 中,我们需要抛出 Error 对象。

    throw new Error('Ran out of coffee')

try...catch

也可以用到 try...catch

    try {
        // codes
    } catch (e) {}

全局错误处理

你还可以设置全局错误处理程序来捕捉未处理的异常

process.on('uncaughtException', (err) => { //  捕捉所有没有被catch到的错误
   console.error('Uncaught exception:', err);
   process.exit(1);
});

小结

nodeJS 的错误处理的区别还是不大的。