问题
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)
}
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
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?
回答1:
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.
Specifically net::ERR_FILE_NOT_FOUND
"does not indicate a fatal error. Typically this error will be generated as a notification".
So the best approach is to attach onloadend
handler to XMLHttpRequest
, triggered on Ajax request complete (either in success or failure).
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
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:///..."
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).
So the code could be:
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();
});
}
来源:https://stackoverflow.com/questions/48127436/how-to-catch-chrome-error-neterr-file-not-found-in-xmlhttprequest