小编Nev*_*ngi的帖子

如何捕获 XMLHttpRequest 的 onload 方法中抛出的错误

我正在从我的对象的方法throw中获取异常。但是我无法使用块来解决该错误。onloadXMLHttpRequestcatchtry catch

\n\n

我的函数中有以下代码_fetch(url, callback)

\n\n
const xhr = new XMLHttpRequest()\n\nxhr.onload = function () {\n  if (xhr.readyState === xhr.DONE) {\n    // if (xhr.status === 200) callback(xhr.response)\n\n    // throw a \'custom\' error if the server responds with 501\n    if (xhr.status === 501) throw new Error(\'Answer not found\') /\n  }\n}\n\n// rest of the fn\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后,我正在使用该_fetch功能:

\n\n
try {\n  _fetch(endPoint, response => console.log(response))\n} catch (error) { // error not caught\n  console.log(error)\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n …

javascript ajax xmlhttprequest

3
推荐指数
1
解决办法
4222
查看次数

标签 统计

ajax ×1

javascript ×1

xmlhttprequest ×1