Good morning. What should happen for onerror xhr to work? The server sometimes returns json data with a code of 500, and according to the logic in this case, onerror should occur, but onload occurs.

var requestError = function () { console.log("error", this); }; var xhr = new XMLHttpRequest(); xhr.open("POST", 'https://core.lotus-app.ru/1/' + method, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.responseType = "json"; xhr.onload = success; xhr.onerror = requestError; xhr.timeout = timeout; xhr.vars = vars; xhr.send(paramToURL(params)); 

code 500

  • And the server just gives the code 500? just some give the code 200, and in json the code 500: D - Sultanov Shamil
  • json data with code 500 and code 500 are different things. Accordingly, the server should not return the Status Code:200OK with json, but 500. On a server, for example, php will look something like this header('HTTP/1.1 500 Internal Server Error'); - Alexey Shimansky
  • @ Alexey Shimansky Server gives 500 in the status code, this code is also observed in the browser console. - Sviatoslav Zaytsev
  • So far, I did this: I added a response check to onload and if not 200, I’ll call onerror. Is it possible to do this without these crutches? - Sviatoslav Zaytsev

1 answer 1

 согласно логике в этом случае должно произойти onerror 

No, it should not. onerror is triggered when a network level error occurs.
Those. if the request is not returned at all or denied due to cross-domain restrictions.

If the http request is returned at all, even with an error code, then onerror will not work.

It is necessary to use onreadystatechange and check the request completion code there.

It is even better to immediately take some kind of wrapper to work with the network at the level of which this subtlety, as well as many subtleties that you have not yet encountered, are resolved for you. Whether it be fetch-polyfill , axios or even $.ajax in case you have jQuery all the same.

  • Is this behavior due to the XHR specification or is it such an implementation of the specification by individual browsers? - Dmitry
  • @Dmitry, as far as I know the specification, because this behavior seems everywhere. But I did not find a specific line of the specification. - Duck Learns to Take Cover