Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  108] [ 4]  / answers: 1 / hits: 19833  / 9 Years ago, mon, october 26, 2015, 12:00:00

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


More From » async-await

 Answers
223

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)
}

[#64594] Friday, October 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shaynelandenb

Total Points: 293
Total Questions: 97
Total Answers: 94

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;