question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to get the response json on HTTP error 400+ ?

See original GitHub issue

Suppose I create a request to http://example.com/404, and the response is 404 status code with a json response like this:

{
  "type": "error",
  "message": "What you were looking for isn't here."
}

How can I get the above json using fetch?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:15 (2 by maintainers)

github_iconTop GitHub Comments

90reactions
nikravicommented, Dec 9, 2016

Here is the code similar to @lasergoat, but handles json regardless of the response.status. Also in case of network error, rejects with a custom error object


/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON, status from the response
 */
function parseJSON(response) {
  return new Promise((resolve) => response.json()
    .then((json) => resolve({
      status: response.status,
      ok: response.ok,
      json,
    })));
}

/**
 * Requests a URL, returning a promise
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 *
 * @return {Promise}           The request promise
 */
export default function request(url, options) {
  return new Promise((resolve, reject) => {
    fetch(endpoint  + url, options)
      .then(parseJSON)
      .then((response) => {
        if (response.ok) {
          return resolve(response.json);
        }
        // extract the error from the server's json
        return reject(response.json.meta.error);
      })
      .catch((error) => reject({
        networkError: error.message,
      }));
  });
}

20reactions
lasergoatcommented, Oct 1, 2015

Hey, just want to let you know, I settled on a fair way of doing what I needed. I thought I’d post just in case anyone else ends up in a situation similar to me where they couldn’t use a catch because fetch gives a ReadableByteStream instead of a json object.

// filename: api.js

export default function api(uri, options = {}) {

  options.headers = {
    'Accept': 'application/json',
    'Authorization': `Bearer ${token}`
  };

  return new Promise((resolve, reject) => {

    fetch(endpoint + uri, options)

      .then(response => {

        if (response.status === 200) {

          return resolve(response.json());

        } else {

          return reject(response.status, response.json());

        }
      });
  });

}

This solution keeps your code clean and semantic. You use it like this:

    api(`user/${id}`).then(result => {
      console.log('success');
      dispatch(receiveUser(result))
    })
    .catch((status, err) => {
      console.log('err');
      console.log(err);
    });
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to get the response json on HTTP error 400 in Java
http post request (json data) · get an error message from response. If you only want to use HttpsURLConnection .Like @Smile says, use...
Read more >
HTTP status and error codes for JSON | Cloud Storage
HTTP status and error codes for JSON · 302—Found · 303—See Other · 304—Not Modified · 307—Temporary Redirect · 308—Resume Incomplete · 400—Bad...
Read more >
How to get JSON response body if status is 400 Bad Request
A 400 error is usually a malformed request. In this case, the error looks like a business rule violation. Either read the 3rd...
Read more >
Response codes - The REST API basics - Akeneo API
All the responses you can get when requesting via the REST API ... HTTP/1.1 400 Bad Request { "code": 400, "message": "Invalid json...
Read more >
JSON getting 400 error in Rest API call - MuleSoft Help Center
I am getting a response code 400 error. HTTP(JSON/POST) -> Dataweave-> setpayload-> HTTP call with header application/json. getting 422 when i try the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found