I’m just learning React, so if my questions are a bit naive, sorry for that
Currently I’m creating a small React app, which fetch news via api and display them with some additional features
The problem I faced, is that I cannot catch error (error.status etc.) if my fetch failed
I tried to add .catch block and catch the error, but somehow it doesn’t work for me, the next question which comes – how to redirect to Error page in case of rejected promise, is it possible to do in fetch function directly?
Here is the fetch function:
function getSearchResult() {
fetch(apiUrl)
.then(res => res.json())
.then(data => setSearchResult(data))
}
If I got data, everything works fine, however, I cannot make any progress with error handling
3
Answers
You can use async await syntax
Async await is more clean but if you don’t want the above syntax you can try this
Method 1:
You can add
.catch()
after the.then()
:Method 2:
Use
try
&catch
instead.try this
try catch
block please