【发布时间】:2018-06-16 01:58:51
【问题描述】:
我想创建能够读取本地文件并使用其中编写的代码的 chrome 扩展程序。我的简单代码是:
const readFile = (filePath) => {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest()
xhr.onerror = (error) => {
reject(error)
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
resolve(xhr.response)
}
}
xhr.ontimeout = function () {
reject('timeout')
}
xhr.open('GET', filePath)
xhr.send()
})
}
async function () {
const code = await readFile(jsFilePath)
console.log(code)
}
当我的文件路径正确时,此代码成功运行。但是当它不是 Chrome 控制台时会抛出这个错误:
GET file:///home/maxim/Documents/test.jsa net::ERR_FILE_NOT_FOUND
通常的 try/catch 块不起作用
async function () {
try {
const code = await readFile(jsFilePath)
console.log(code)
} catch (e) {
console.log(e)
}
}
我怎样才能捕捉到这种类型的错误?
【问题讨论】:
-
使用
xhr.onloadend = e => e.type !== 'error' ? resolve(xhr.response) : reject(e)监听器代替onerror和onreadystatechange -
不幸的是,这对我的情况没有帮助。 e.type 返回 'loadend' 并且 chrome 抛出 net::ERR_FILE_NOT_FOUND。
-
在 try 和 catch 中添加另一个 console.log 并查看实际打印的是哪个
标签: javascript google-chrome google-chrome-extension