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?
The Failed to load resource: net::ERR_FILE_NOT_FOUND means that a file can't be found. This can occur because there's the file doesn't exist, it's in a different directory than the one we specified, or its in the correct place but the name doesn't match the name specified.
It may have been moved, edited or deleted.
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();
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With