2

This how I call fetch

fetchOpts = {...}
return fetch(url, fetchOpts)
    .then(checkStatus)

The url I call will always return a json data, even in the error condition:

{error_message:"Encountered issue with update"
status:"error",
status_code:400}

I would like to get hold of the error_message field value and pass to the Error constructor.

Inside checkStatus, it handles exception this way:

function checkStatus(response) {
  let error = null;

  if (!response.headers.get('Content-Type').includes('application/json')) {
    error = new Error(response.statusText);
    error.response = response;
    throw error;
  }

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

  if (response.ok) {
    return response;
  }
  const jsonData = response.json() ; // <- `jsonData` is a promise
  error = new Error(/* How to extract error_message from json data? */);
  error.response = response;
  throw error;
}

I have checked this question already but it does not really address my need fetch: Reject promise with JSON error object. Also the accepted answer seems, based on the comments, not to resolve OP's question entirely.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304

2 Answers2

1

I may be misunderstanding the problem, but the error_message member is exposed as a property of the data object the promise returns, right? So it seems like you could just do this:

response.json()
.then(jsonData => {
  if (jsonData.error_message) {
    error = new Error(jsonData.error_message)
  }
}
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
1

If you change your last bit of code to

return response.json().then(json => {
    error = new Error(json.error_message);
    error.response = response;
    throw error;
}

That should do what you want

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87