问题描述
我想创建chrome扩展,它将能够读取本地文件并使用其中编写的代码。我简单的代码是:
I want to create chrome extension which will be able to read local files and use code wrote in them. My simplyfied code is:
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)
}
当我的filePath正确时,此代码成功运行。但是当它不是Chrome控制台时会抛出此错误:
This code successfully works when my filePath is correct. But when it is not Chrome console throws this error:
GET file:///home/maxim/Documents/test.jsa net::ERR_FILE_NOT_FOUND
通常的try / catch块不起作用
Usual try/catch block doesn't work
async function () {
try {
const code = await readFile(jsFilePath)
console.log(code)
} catch (e) {
console.log(e)
}
}
我怎样才能发现这类错误?
How can I catch this type of errors?
推荐答案
首先 net :: ERR_FILE_NOT_FOUND
是一个浏览器错误(请参阅,,因此您无法使用JS代码捕获它。
First of all net::ERR_FILE_NOT_FOUND
is a browser error (see Chromium/Chrome error list, Chrome fail error codes, so you cannot catch it with JS code.
具体来说, net :: ERR_FILE_NOT_FOUND
并不表示致命错误。通常此错误将作为通知生成。
Specifically net::ERR_FILE_NOT_FOUND
"does not indicate a fatal error. Typically this error will be generated as a notification".
所以最好的方法是将 onloadend
处理程序附加到 XMLHttpRequest
,在Ajax请求完成时触发(或者成功或失败)。
So the best approach is to attach onloadend
handler to XMLHttpRequest
, triggered on Ajax request complete (either in success or failure).
但是你无法检查状态,实际上是状态值
, statusText
和 readyState
的属性XMLHttpRequest
两者在文件存在的情况下和在文件不存在的情况下发现总是:
But you cannot check the status, in fact values of status
, statusText
and readyState
properties of XMLHttpRequest
both in the case of file existing and in the case of file not found are always:
status: 0
statusText: ""
readyState: 4
相反,您可以查看属性回复
, responseText
和 responseURL
当找不到文件时,其值为,或者在其他情况下:
On the contrary you can check the properties response
, responseText
and responseURL
whose value is "" when the file is not found or in other cases:
response: <file content>
responseText: <file content>
responseURL: "file:///..."
要检查的其他值是事件
(ProgressEvent)已加载
属性,如果找不到文件,则其值为0(或在其他情况下加载的字节数) )。
Other value to check is event
(ProgressEvent) loaded
property which has value 0 in case of file not found (or the bytes loaded in other cases).
所以代码可以是:
const readFile = (filePath) => {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest()
xhr.onloadend = (event) => {
console.log("xhr.onloadend", event, xhr.status, xhr.statusText, xhr.readyState, xhr);
if (event.loaded && xhr.response) {
resolve(xhr.response);
} else {
reject("error");
}
}
xhr.open('GET', filePath);
xhr.send();
});
}
这篇关于如何在XMLHttpRequest中捕获Chrome错误网:: ERR_FILE_NOT_FOUND?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!