基本上,
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)
是您可以做的最好的事情,对于大多数(如果不是全部)错误,这都是正确的。因此,我建议您使用该
pre属性并检查其值:
if (err.pre === 'ENOENT') { console.log('File not found!');} else { throw err;}这样,您仅处理该特定错误,然后重新抛出所有其他错误。
或者,您也可以访问错误的
message属性以验证详细的错误消息,在这种情况下,该消息是:
ENOENT, no such file or directory 'foo.bar'
希望这可以帮助。



