(请原谅我的英文)
我现在正在学习 javascript promises。 下面的示例代码是 node.js 的简单 javascript 代码(我的 node.js 版本是 v10.0.0),它使用 promise 链异步读取和解析 JSON 文件。
const fs = require("fs");
function readFileAsync(filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, 'utf8', (error, result) => {
if (error)
reject(error);
else
resolve(result);
});
});
}
readFileAsync('test.json')
.then(res => JSON.parse(res))
.then(res => { console.log('JSON=', res); })
.catch(err => { console.log(err.message); });
我发现这个示例代码会生成不同格式的错误信息。 例如,如果它找不到 'test.json',则错误消息是...
ENOENT: no such file or directory, open '/home/node/test.json'
如果它不能解析'test.json',错误信息是...
Unexpected token / in JSON at position 31
我想修改示例代码以生成始终包含 JSON 文件名的相同格式的错误消息。
为此,首先我应该知道 promise 链的哪一部分导致了错误。我怎么知道?
最佳答案
有两种方法可以达到你想要的效果。
Promise.then
有两个参数,见下面的代码和 you can get more information here
readFileAsync('test.json')
.then(res => JSON.parse(res))
.then(res => { console.log('JSON=', res); }, error => {
// here can catch error of previous then function
});
另一种方法是修改函数readFileAsync
function readFileAsync(filename) {
return new Promise(resolve => {
fs.readFile(filename, (error, result) => {
if (error)
resolve(null); // you can resolve whatever you want
else
resolve(result);
});
});
}
并且 .catch()
不会捕获任何 readFileAsync
的错误。
关于Javascript promise : Can I know which part of promise chain caused error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203835/