0

That's pretty simple, I have an API that returns HTTP 412 and JSON description of the error.

Status Code:412 PRECONDITION FAILED

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8000
Access-Control-Expose-Headers:access-token, expiry, uid
Content-Length:224
Content-Type:application/json
Date:Wed, 09 Mar 2016 16:31:39 GMT
Server:Werkzeug/0.9.6 Python/3.5.1
{
  "errors": {
    "email": [
      "This field is required."
    ],
    "password": [
      "String value is too short."
    ],
    "password_confirmation": [
      "doesn't match Password"
    ]
  },
  "status": "error"
}

Is it possible for me in my javascript (ES6) to fetch my url and get a grip on BOTH information that I need:

  • HTTP code
  • parsed Json
export function checkHttpStatus(response) {
  console.log(response);
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  throw error;
}
export function parseJSON(response) {
  return response.json();
}
return fetch(getRegisterUrl(), {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(body)
})
.then(checkHttpStatus)
.then(parseJSON);

If i parseJSON before headers, the response.status is not available anymore. If I parse header before json, i throw an exception BEFORE getting a chance to get my JSON body.

Is there a way to handle this ?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Guibod
  • 371
  • 1
  • 3
  • 13
  • 1
    The only thing that's preventing you from doing that is your own code structure... Just write it differently...!? – deceze Mar 09 '16 at 16:49
  • sure, just mod checkhttpstatus(), since that's the ONLY thing checking the http code. `if (response is 200 OR response is 414) { return response }` – Marc B Mar 09 '16 at 16:50
  • 1
    I've got an alternative answer there: http://stackoverflow.com/questions/29473426/fetch-reject-promise-with-json-error-object#answer-29475662 – Guibod Mar 09 '16 at 17:22

0 Answers0