最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it ok to mix .catch() with asyncawait for error handling? - Stack Overflow

programmeradmin2浏览0评论

Normally when it comes to error handling for async/await in JavaScript, people default to use try/catch. But I wonder if I can use .catch() instead, as in


  const res = await fetch().catch((error) => (
    // error handling
  ));

  const json = await res.json();

I wonder if this works the same as a try/catch block

  try {
    const res = await fetch()
    const json = await res.json();
  } catch(e) {
    // error handling
  }  

I understand that technically the try/catch block can catch errors raised from res.json(); as well, so I guess it is still preferable to the .catch() example?

Normally when it comes to error handling for async/await in JavaScript, people default to use try/catch. But I wonder if I can use .catch() instead, as in


  const res = await fetch().catch((error) => (
    // error handling
  ));

  const json = await res.json();

I wonder if this works the same as a try/catch block

  try {
    const res = await fetch()
    const json = await res.json();
  } catch(e) {
    // error handling
  }  

I understand that technically the try/catch block can catch errors raised from res.json(); as well, so I guess it is still preferable to the .catch() example?

Share Improve this question edited Jul 31, 2022 at 23:30 Bergi 665k161 gold badges1k silver badges1.5k bronze badges asked Jul 31, 2022 at 22:07 JojiJoji 5,62510 gold badges56 silver badges116 bronze badges 2
  • 4 The problem is that if you catch an error like this, the function would proceed and res.json() would run. It would throw an error or it would just return nothing I'm not sure, but it will cause an expected bahaviour. – Konrad Commented Jul 31, 2022 at 22:17
  • Your first example needs a then() instead of await, so you can parse the json and then catch any errors: fetch(bla).then(res => res.json()).catch(err). – Kokodoko Commented Jul 31, 2022 at 22:27
Add a comment  | 

1 Answer 1

Reset to default 19

I wonder if this works the same as try/catch block

No - as you've already answered yourself. In particular, the try block around res.json() would also catch errors thrown from that, which you may or may not want.

Also, if you aren't re-throwing an exception from your .catch() callback, its return value will become the res value and res.json() is still called on it, so you better return a valid Response instance.

Is it ok to mix .catch() with async/await for error handling?

Yes, absolutely! It's a much more versatile tool if you want to handle errors from one specific promise only. Doing that with try/catch is much more ugly, so I would even recommend using .catch() for re-throwing errors (when you want a better error message):

const res = await fetch(…).catch(error => {
  throw new Error('Could not reach backend', {cause: error});
});
if (!res.ok) throw new Error(`Backend responded with ${res.status} error: ${await res.text()}`);
const data = await res.json();

If you don't want to re-throw, I recommend using .then() to handle success and failure paths separately:

const data = await fetch(…).then(res => {
  if (!res.ok) {
    console.error(`Backend responded with ${res.status} error`);
    return null;
  }
  return res.json();
}, error => {
  console.error('Could not reach backend', error);
  return null;
});
发布评论

评论列表(0)

  1. 暂无评论