Freduah Gideon
Freduah Gideon

Reputation: 1350

Fetch Api .then functions runs even if response.ok is false

I'm trying to fetch a resource from my local network using the fetch api

After fetching i want to check the response type and act accordingly

But when i receive a status of 500 and i try to return an error callback, the .then() function which was supposed to run only when the response.ok was false runs either way

fetch(testUrl, { headers, method: "POST" })
.then(response => {
if (response.status === 200) { return response.json() }
if (response.status === 401) { Logout() }
if (response.status === 500) {
return setTestApiFetchError({
    'error_type': "SERVER_ERROR",
    "error": true
})
}
})
.then(data => console.log(Data))

the function.then(data => console.log(data)) runs irrespectively

Upvotes: 0

Views: 16336

Answers (2)

ZeroWolfCode
ZeroWolfCode

Reputation: 105

Here are a couple links that might help: How can I pass JSON body of Fetch response to Throw Error() with then()? https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch https://usefulangle.com/post/314/javascript-fetch-error-handling

As Ali mentioned, you'd want to reject or throw the 500 response to get it into a catch block. Personally, I'd simply check if response.ok, then handle any errors in the catch:

fetch(testUrl, { headers, method: "POST" })
.then((response,reject)=> {
 if (response.ok) return response.json();
return Promise.reject(rejectReponse)
})
.then(success)
.catch(fail)

Or, if you're able to use async/await:

try{
    const response = await fetch(testUrl, { headers, method: "POST" });
     if (!response.ok) throw response;
     //response is 200-209
    const data = await response.json();
    //etc.
}catch(e){
    if (e.status === 401) logout();
    //handle server/client errors
}

Upvotes: 2

Ali
Ali

Reputation: 136

you need to handle your promise with the resolve and reject arguments

try it like this

const tt =  fetch(testUrl, { headers, method: "POST" })
.then((response,reject)=> {
    const rejectReponse= {
    "error_type": "SERVER_ERROR",
    "error": true
  }
    if (response.ok === true) return response.json() 
        else if (response.status===500) return  reject (rejectReponse)
        })
    
    tt.then(x=>console.log(x)).then(undefined,x=>console.log(x))

to learn more check promises in this article: https://learnjsx.com/category/2/posts/es6-promise

Upvotes: 0

Related Questions