Good day. Can you please tell if the onerror event works in a synchronous request. Thank.

My code is:

var xhr = new XMLHttpRequest(); xhr.open('GET',"/customer/"+login,false); xhr.onerror = function(){ alert("XMLHttpRequest error"); console.log("XMLHttpRequest error"); authorizedCustomer = new Customer("Username","Password"); authorizedCustomer.authorities = [{"name":"ROLE_ADMIN"}]; alert(JSON.stringify(authorizedCustomer)); return; } xhr.send(); authorizedCustomer = JSON.parse(xhr.responseText); 

but, when working in the background (without communication with the server), the error code does not work.

  • which browser are you trying in? - Grundy
  • judging by the specification, browsers should now throw an exception when using synchronous requests not in the webwoker. And if you look at error handling , then with a synchronous request there should be an exception. - Grundy

1 answer 1

To get error codes in XMLHttpRequest, I use this code

 var xhr = new XMLHttpRequest(); var readyStateChange = function () { if (xhr && xhr.readyState == 4) { var status = xhr.status; // статус-код запроса, 200-все хорошо, 404-страница не найдена var result = xhr.responseText; // результат запроса // здесь что-то делаешь } }; xhr.onreadystatechange = readyStateChange; xhr.send(); 

  • bad code, since there is no status check itself - Grundy
  • I'm interested in the onerror function. Does it not work in a synchronous request? - Nikolay Egorov
  • in a synchronous request, the status can be checked after send (); if (xhr.status == 200) - akrasnov87
  • This I know, I probably did not quite clearly set out the question ... I need that the code worked not with an error, but with an exception. Those. if send returns this (Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load) exception to make return, and the script goes on ... In the asynchronous I intercept it xhr.onerror ... - Nikolay Egorov