如何在XMLHttpRequest中捕获Chrome错误网::: ERR_FILE_NOT_FOUND?

Max*_*chu 4 javascript google-chrome google-chrome-extension

我想创建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)
}
Run Code Online (Sandbox Code Playgroud)

当我的filePath正确时,此代码成功工作。但是如果不是,Chrome控制台会抛出此错误:

GET file:///home/maxim/Documents/test.jsa net::ERR_FILE_NOT_FOUND
Run Code Online (Sandbox Code Playgroud)

通常的try / catch块不起作用

async function () {
  try {
    const code = await readFile(jsFilePath)
    console.log(code)
  } catch (e) {
    console.log(e)
  }
}
Run Code Online (Sandbox Code Playgroud)

如何捕获此类错误?

bea*_*ver 6

首先net::ERR_FILE_NOT_FOUND是浏览器错误(请参阅Chromium / Chrome错误列表Chrome失败错误代码,因此您无法使用JS代码捕获它。

具体地net::ERR_FILE_NOT_FOUND“不表示一个致命错误。典型地,该错误将作为通知来生成”。

所以,最好的办法是附加onloadend处理程序XMLHttpRequest,触发Ajax请求完成后(无论是成功或失败)。

但是,您无法检查status,实际上status,在存在文件的情况下和在找不到文件的情况下,的值statusTextreadyState属性XMLHttpRequest始终是:

status: 0
statusText: ""
readyState: 4
Run Code Online (Sandbox Code Playgroud)

相反,你可以检查的属性responseresponseText并且responseURL其值是“”的时候,找不到文件或在其他情况下:

response: <file content>
responseText: <file content>
responseURL: "file:///..."
Run Code Online (Sandbox Code Playgroud)

要检查的其他值是event(ProgressEvent)loaded属性,如果找不到文件(或在其他情况下加载的字节),则该属性值为0。

因此代码可能是:

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();
    });
}
Run Code Online (Sandbox Code Playgroud)