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
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.
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. ...
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.
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).
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With