Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch response body using fetch in case of HTTP error 422?

I have an API on backend which sends status 201 in case of a successful call and if there's any error with the submitted data it sends status 422 (Unprocessable Entity) with a json response like below:

{
  "error": "Some error text here explaining the error"
}

Additionally it sends 404 in case API fails to work on back end for some reason.

On the front-end I'm using the below code to fetch the response and perform a success or error callback based on response status code:

fetch("api_url_here", {
    method: 'some_method_here', 
    credentials: "same-origin",
    headers: {
      "Content-type": "application/json; charset=UTF-8",
      'X-CSRF-Token': "some_token_here"
    }
    })
  .then(checkStatus)
  .then(function json(response) {
    return response.json()
  })
  .then(function(resp){
    successCallback(resp)
  })
  .catch(function(error){
    errorCallback(error);
  });
  
//status function used above
checkStatus = (response) => {
  if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response)
  } else {
    return Promise.reject(new Error(response))
  }
}

The successCallback function is able to receive the response in proper JSON format in case of status code 201 but when I try to fetch the error response in errorCallback (status: 422) it shows something like this (logging the response in console):

Error: [object Response]
    at status (grocery-market.js:447)

When I try to console.log the error response before wrapping it in new Error() like this,

  checkStatus = (response) => {
    if (response.status >= 200 && response.status < 300) {
      return Promise.resolve(response)
    } else {
      console.log(response.json()) //logging the response beforehand
      return Promise.reject(new Error(response.statusText))
    }
  }

I get the below promise in console (the [[PromiseValue]] property actually contains the error text that i require)

enter image description here

Can someone please explain why this is happening only in error case, even though I'm calling response.json() in both error and success case?

How can I fix this in a clean manner?

EDIT: I found that if I create another json() promise on the error response I am able to get the correct error :

fetch("api_url_here", {
    method: 'some_method_here', 
    credentials: "same-origin",
    headers: {
      "Content-type": "application/json; charset=UTF-8",
      'X-CSRF-Token': "some_token_here"
    }
    })
  .then(checkStatus)
  .then(function json(response) {
    return response.json()
  })
  .then(function(resp){
    successCallback(resp)
  })
  .catch(function(error){
    error.json().then((error) => { //changed here
        errorCallback(error)
      });
  });

But why do I have to call another .json() on the response in error case?

like image 468
D_S_X Avatar asked Aug 14 '20 07:08

D_S_X


People also ask

How do I get the HTTP response fetch error message?

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response. ok property to see if the request failed and reject the promise ourselves by calling return Promise. reject(error); .

How do you get a response body in node fetch?

The code that follows serves as an illustration of this point. const fetch = require('node-fetch'); //npm install node-fetch fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) . then(res => res. json()) .

Does fetch work with HTTP?

Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP. The fetch specification differs from jQuery.ajax() in the following significant ways: The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500.

How do I get response json from Fetch?

To get JSON from the server using the Fetch API, you need to use the JavaScript fetch() method. Then you need to call the response. json() method to get the JSON. The "Accept: application/json" header tells the server that the client expects a JSON response.


2 Answers

Short answer

Because your assumption that you parse the response content twice is incorrect. In the original snippet, the then after the then(checkStatus) is skipped when the error condition is met.

Long answer

In general, well-structured promise chain consists of a:

  1. Promise to be fulfilled or rejected sometime in the future
  2. then handler that is run only upon fulfillment of the Promise
  3. catch handler that is run only upon rejection of the Promise
  4. finally (optional) that is run when a Promise is settled (in either 2 or 3)

Each of the handlers in 2 and 3 return a Promise to enable chaining.

Next, fetch method of the Fetch API rejects only on network failures, so the first then method is called regardless of the status code of the response. Your first handler, the onFulfilled callback returns either a fulfilled or rejected Promise.

If fulfilled, it passes control to the next then method call in the chain, where you extract JSON by calling json method on the response, which is then passed as Promise value to the last then method to be used in the successCallback.

If rejected, the control is passed to the catch method call, which receives the Promise with the value set to new Error(response) that you then promptly pass to errorCallback. Therefore, the latter receives an instance of Error, whose value is an instance of Response from Fetch API.

That is exactly what you see logged: Error: [object Response], a result of calling toString method on an instance of Error. The first part is the constructor name, and the second is a string tag of the contents (of the form [type Constructor]).

What to do?

Since your API returns JSON response for every possible use case (201, 404, 422), pass the parsed response to both fulfilled and rejected promise. Also, note that you accidentally declared checkStatus on the global scope by omitting a var, const, or let keyword:

//mock Response object
const res = {
  status: 200,
  body: "mock",
  async json() {
    const {
      body
    } = this;
    return body;
  }
};

const checkStatus = async (response) => {

  const parsed = await response.json();

  const {
    status
  } = response;

  if (status >= 200 && status < 300) {
    return parsed;
  }

  return Promise.reject(new Error(parsed));
};

const test = () => {

  return checkStatus(res)
    .then(console.log)
    .catch((err) => console.warn(err.message))
    .finally(() => {
      if (res.status === 200) {
        res.status = 422;
        return test();
      }
    });

};

test();

Additionally, since you already use ES6 features (judging by the presence of arrow functions), why not go all the way and use the syntactic sugar async/await provides:

(() => {
  try {
    const response = await fetch("api_url_here", {
      method: 'some_method_here',
      credentials: "same-origin",
      headers: {
        "Content-type": "application/json; charset=UTF-8",
        'X-CSRF-Token': "some_token_here"
      }
    });

    const parsed = await response.json(); //json method returns a Promise!

    const {
      status
    } = response;

    if (status === 201) {
      return successCallback(parsed);
    }

    throw new Error(parsed);

  } catch (error) {
    return errorCallback(error);
  }
})();

Note that when you are passing the parsed JSON content to the Error() constructor, an abstract ToString operation is called (see step 3a of the ECMA spec).

If the message is an object, unless the original object has a toString method, you will get a string tag, i.e. [object Object], resulting in the content of the object being inaccessible to the error handler:

(() => {

  const obj = { msg : "bang bang" };
  
  const err = new Error(obj);
  
  //will log [object Object]
  console.log(err.message);
  
  obj.toString = function () { return this.msg; };
  
  const errWithToString = new Error(obj);

  //will log "bang bang"
  console.log(errWithToString.message);

})();

Contrary, if you reject a Promise with the object passed as an argument, the rejected Promise's [[PromiseValue]] will be the object itself.

like image 198
Oleg Valter is with Ukraine Avatar answered Sep 17 '22 14:09

Oleg Valter is with Ukraine


It's because in case of an error then handlers are skipped and the catch handler is executed, checkStatus returns a rejected promise and the remaining then chain is bypassed.

This is how I'd refactor your code.

checkStatus = async (response) => {
    if (response.status >= 200 && response.status < 300) 
      return await response.json()

    throw await response.json()
  }
}


fetch("api_url_here", {
    method: 'some_method_here', 
    credentials: "same-origin",
    headers: {
      "Content-type": "application/json; charset=UTF-8",
      'X-CSRF-Token': "some_token_here"
    }
    })
  .then(checkStatus)
  .then(successCallback)
  .catch(errorCallback);

P.S. this code can be made a bit better to look at visually by using async/await

like image 32
hackhan Avatar answered Sep 18 '22 14:09

hackhan