try..catch not catching async/await errors

前端 未结 1 449
萌比男神i
萌比男神i 2020-11-27 22:40

Perhaps I misunderstood how catching errors with async/await is supposed to work from things articles like this https://jakearchibald.com/2014/es7-async-functio

1条回答
  •  抹茶落季
    2020-11-27 22:43

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

    0 讨论(0)
提交回复
热议问题