关于因错误或未定义而导致的开发人员错误,或可能导致整个应用崩溃的其他事情:
我应该使用这个吗?
var domain = require('domain');
var d = domain.create();
d.on('error', function(err) {
console.error(err);
});
d.run(function() {
if (someom.sadjaslkd.asdasd=="yes") console.log("Yes");
// run more other things in the safe area
});
可能someom.sadjaslkd.asdasd
未定义。
或者我应该使用这个:
try {
if (someom.sadjaslkd.asdasd=="yes") console.log("Yes");
// run more other things in the safe area
} catch(err) {
// handle the error safely
}
关于不是由于客户的错误而由于错误而造成的操作错误:
我应该使用这个吗?
if (somethingWorng) res.status(400).json({status: "400", error: "Some custom error message to the user"});
或者也许我应该通过这样的错误:
if (somethingWorng) throw "Some custom error message to the user";
或者也许
if (somethingWorng) throw new Error("Some custom error message to the user");
确实有大量的方法可以完成这项工作。有没有一种快速,容易理解的最佳实践?