Home > OS >  Need to get the response status after error handle errors
Need to get the response status after error handle errors

Time:10-21

My problem is when the fetch response status is 403 the response return HTML not json, but when the code reach the if statment i cant access the response status anymore.

const response = await fetch(
   \\\\\\ Fetch infos \\\\\
).then(
    response => {
        return response.json().then(data => ({
            status: response.status,
            data

        })).catch(err => console.log(err))
    });

if (response.status == 403) {
  \\\\ Stuf \\\\\
}

CodePudding user response:

await fetch(URL)
  .then((response) => {
    if (!response.ok && response.status === 403) {
      // Write your logic here and return
    }
    return response.json();
  })
  .then((data) => ({
    data,
  }));

CodePudding user response:

Before returning response.json() check the status and if response.ok

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then((response) => {
    console.log(response)
    if (response.ok && response.status === 200) {
      return response.json()
    } else if (response.status === 403) {
      // do what ever you want to do
    }

  })
  .then(json => console.log(json))

  • Related