Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try..catch not catching async/await errors

Perhaps I misunderstood how catching errors with async/await is supposed to work from things articles like this https://jakearchibald.com/2014/es7-async-functions/ and this http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html, but my catch block is not catching 400/500.

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

example on codepen if it helps

like image 888
azium Avatar asked Oct 26 '15 20:10

azium


People also ask

Do I need to use try/catch () with async/await?

I'll also explain why you rarely need anything but catch () with async functions. When you're first getting started with async/await, it is tempting to use try/catch around every async operation. That's because if you await on a promise that rejects, JavaScript throws a catchable error.

How to handle error in async await in JavaScript?

Async Await Error Handling in JavaScript 1 try/catch. When you're first getting started with async/await, it is tempting to use try/catch around every async operation. 2 Golang in JS. Another common pattern is using .then () to convert a promise that rejects into a promise that fulfills with an error. 3 Using catch () on the Function Call. ...

How do I catch an error in an async function?

When an error is thrown in an async function, you can catch it with a try {} catch {}. So this works as you'd expect: This is syntax sugar for what you might have been doing with promises earlier: In fact, anywhere you use the keyword await, you can remove await and do the traditional .then () and .catch () calls.

How to call thisthrows () in an async/await function?

We call thisThrows () in an async function and await the thisThrows () function. We chain the thisThrows () function call with a .catch () call. The first solution would look like this: Both solutions work fine, but the async/await one is easier to reason about (at least in my personal opinion).


1 Answers

400/500 is not an error, it's a response. You'd only get an exception (rejection) when there's a network problem.

When the server answers, you have to check whether it's good or not:

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)
}
like image 194
Bergi Avatar answered Oct 04 '22 02:10

Bergi