Fetch Network Error
Unanswered
Carolina Dog posted this in #help-forum
Carolina DogOP
So I'm building an app where it shoots an API end point with fetch. I tried tbis code
When i tried in localhost, the network error is handled. But when I tried in production, the network error is not handled. Is there a way to handle network error in fetch? Or should I just set a timeout to set the fetch request is failed? Thanks!
fetch(url, { method: "POST", body: formData })
.then((res) => {
if (res.ok) {
toast.success()
} else {
toast.error()
}
})When i tried in localhost, the network error is handled. But when I tried in production, the network error is not handled. Is there a way to handle network error in fetch? Or should I just set a timeout to set the fetch request is failed? Thanks!
1 Reply
Carolina DogOP
For those who are wondering, after a few experiments,
the try {fetch} catch {} only works when the connection is lost BEFORE it fetches. So it's impossible to detect lost connection. The only way to handle this is just set timeout on fetch using
the try {fetch} catch {} only works when the connection is lost BEFORE it fetches. So it's impossible to detect lost connection. The only way to handle this is just set timeout on fetch using
const controller = new AbortController();. When the connection is up again, it continues fetching. But after t seconds, the fetch will abort and throw an Error so u can catch it using try {} catch{}.