20

おそらく、このhttps://jakearchibald.com/2014/es7-async-functions/やこのhttp://pouchdb.com/2015/03/05/taming-async/awaitのような記事から、エラーをキャッチする方法がどのように機能するかを誤解しましたthe-async-beast-with-es7.htmlですが、私のブロックは 400/500 をキャッチしていません。catch

async () => {
  let response
  try {
   let response = await fetch('not-a-real-url')
  }
  catch (err) {
    // not jumping in here.
    console.log(err)
  }
}()

それが役立つ場合のcodepenの例

4

1 に答える 1

61

400/500 はエラーではなく、応答です。ネットワークに問題がある場合にのみ、例外 (拒否) が発生します。

サーバーが応答したら、それが適切かどうかを確認する必要があります

try {
    let response = await fetch('not-a-real-url')
    if (!response.ok) // or check for response.status
        throw new Error(response.statusText);
    let body = await response.text(); // or .json() or whatever
    // process body
} catch (err) {
    console.log(err)
}
于 2015-10-26T20:38:20.870 に答える