Within node.js readFile() shows how to capture an error, however there is no comment for the readFileSync() function regarding error handling. As such, if I try to use readFileSync() when there is no file, I get the error Error: ENOENT, no such file or directory
.
How do I capture the exception being thrown? The doco doesn't state what exceptions are thrown, so I don't know what exceptions I need to catch. I should note that I don't like generic 'catch every single possible exception' style of try/catch statements. In this case I wish to catch the specific exception that occurs when the file doesn't exist and I attempt to perform the readFileSync.
Please note that I'm performing sync functions only on start up before serving connection attempts, so comments that I shouldn't be using sync functions are not required :-)
ベストアンサー1
基本的に、fs.readFileSync
ファイルが見つからない場合はエラーをスローします。このエラーはError
プロトタイプからのものであり、 を使用してスローされるthrow
ため、キャッチする唯一の方法はtry / catch
ブロックを使用することです。
var fileContents;
try {
fileContents = fs.readFileSync('foo.bar');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
残念ながら、プロトタイプ チェーンを見るだけでは、どのエラーがスローされたかを検出することはできません。
if (err instanceof Error)
これができる最善の策であり、これはほとんどの(すべてではないにしても)エラーに当てはまります。したがって、プロパティを使用してcode
その値を確認することをお勧めします。
if (err.code === 'ENOENT') {
console.log('File not found!');
} else {
throw err;
}
この方法では、この特定のエラーのみを処理し、他のすべてのエラーを再スローします。
あるいは、エラーのmessage
プロパティにアクセスして詳細なエラー メッセージを確認することもできます。この場合は次のようになります。
ENOENT, no such file or directory 'foo.bar'