Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

javascript - 抓取错误(Catching a fetch error)

My understanding is that a piece of code throwing error anywhere in callstack can be caught at final catch block.

(我的理解是,可以在最终catch块中捕获在调用堆栈中任何地方发生的代码抛出错误。)

for fetch error, when no internet is available, when I make APIwithoutCatch in callCallAPI, error is not caught.

(对于获取错误,当没有可用的互联网时,当我在callCallAPI中制作APIwithoutCatch时,未捕获到错误。)

while APIwithCatch catches its own error.

(而APIwithCatch会捕获自己的错误。)

All other errors eg 404, are caught at both places, wherever I want.

(无论我在哪里,所有其他错误(例如404)都会在这两个地方捕获。)

 async function APIwithcatch() { try { var response = await fetch("http://wwww.dfdfdf.com/user.json"); return response; } catch (e) { console.log(e); } } async function APIwithoutcatch() { var response = await fetch("http://wwww.dfdfdf.com/user.json"); return response; } function callCallAPI() { try { // return APIwithcatch(); return APIwithoutcatch(); } catch (e) { console.log(e); } } callCallAPI(); 
My assumption that any error should flow down callstack is correct or not?

(我的假设是任何错误都应沿着调用堆栈流下来,这是正确的还是错误的?)

What is special about net::ERR_INTERNET_DISCONNECTED error?

(net :: ERR_INTERNET_DISCONNECTED错误有什么特别之处?)

  ask by DrEarnest translate from so


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

APIwithoutcatch is an async function - it doesn't throw an exception but rather will reject the promise that it returns.

(APIwithoutcatch是一个async function -它不会引发异常,而是会拒绝它返回的承诺。)

You need to wait for the promise, either with then or await syntax (just like you did await the fetch within APIwithcatch ):

(您需要使用thenawait语法来等待promise(就像您在APIwithcatch await fetch APIwithcatch ):)

async function API() {
  return fetch("http://wwww.example.com/user.json");
}

function callAPI() {
  try {
    await API();
  } catch (e) {
    console.log(e);
  }
}
callAPI();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...