admin管理员组

文章数量:1241150

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?

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?

Share Improve this question asked Jan 6, 2018 at 12:41 Maxim TopchuMaxim Topchu 631 gold badge1 silver badge4 bronze badges 3
  • 1 Use xhr.onloadend = e => e.type !== 'error' ? resolve(xhr.response) : reject(e) listener instead of onerror and onreadystatechange – woxxom Commented Jan 6, 2018 at 13:09
  • Unfortunately this doesn't help in my situation. e.type returns 'loadend' and chrome throws net::ERR_FILE_NOT_FOUND. – Maxim Topchu Commented Jan 9, 2018 at 6:13
  • add another console.log in both try and catch and see which one is actually getting printed – Tarun Lalwani Commented Jan 9, 2018 at 13:06
Add a ment  | 

1 Answer 1

Reset to default 13 +250

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 plete (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();
    });
}

本文标签: javascriptHow to catch Chrome error netERRFILENOTFOUND in XMLHttpRequestStack Overflow