もともと、Robuts の Web サーバーを Node.js ベースで作成する方法について質問したいのですが。しかし、それは非常に大きくて曖昧な質問になる可能性があります。そこで、Robuts Web サーバーを作成するときに直面する、小さくて具体的な質問または課題に分けます。
だから、私が直面している課題の 1 つは、Node.js で未処理のエラーをすべてキャッチする方法ですか? 未処理のエラーによってNode.jsの実行が停止し、Webサーバーがダウンすることを望まないため、これを実行したいと考えています。
思いつく解決策は、サーバーの実行中のコード ブロックを try-catch ブロックに配置して、未処理のエラーをすべてキャッチすることです。ただし、非同期メソッドからエラーが発生した場合、これは機能しません。たとえば、私の Web サーバーは次のコードのようになります。
var fs = require('fs');
var http = require('http');
try {
// Here is my main web server, it could happen errors by adding
// more and more modules and functionalities to my server.
// I need to catch all unhandled errors to prevent server from crashing
// So, I put my whole server running in a try-catch block, but any error from
// an async method could not be caught!
http.createServer(function(req, res) {
throw Error("An unhandled error happens!");
}).listen(1234);
}catch (e){
console.log("An unhandled error caught!")
}
console.log('Server is listening to port 1234');
それで、サーバーが停止しないようにするために、エラー処理の正しい方向に進んでいますか? または、サーバーをエラーから回復させる他のメカニズムがありますか?