0

This is not a duplicate of try-catch doesn't work with XMLHTTPRequest I no longer want to catch the error, I want to prevent the error message to be displayed in the console.


I wrote the following code for Ajax request in JavaScript:

let request = new XMLHttpRequest();

try {

     request.onreadystatechange = success;
     request.open('POST', 'https://urlthatdonotexist.com', true);
     request.send('key=value');
}
catch(e) 
{ 
    document.getElementById('output').textContent = 'error';
    console.log (e);
}



function success()
{

    if (request.readyState != 4) return;
    if (request.status != 200) { document.getElementById('output').textContent = 'error'; return; }
    document.getElementById('output').textContent = 'success';  
    console.log (request);
}

As you can see, the URL does not exists and the following error is generated:

(index):38 POST https://urlthatdonotexist.com/ net::ERR_NAME_NOT_RESOLVED

which is the expected behavior. But as you can see, I expected the error to be catch by the try...catch, and it is not the case as mentionned in this question:

try-catch doesn't work with XMLHTTPRequest

How to prevent the error to be displayed in the console?

I made a JSFiddle here

Fifi
  • 3,360
  • 2
  • 27
  • 53
  • _"the error should be catch by the `try...catch`"_ - Why? `.open()` and `.send()` work exactly as expected. The "error" is just your interpretation of the result of the call. But that's nothing that would require the JavaScript engine to abort a script for. – Andreas Jan 24 '20 at 17:06
  • @Ivar, no, I edited my question. – Fifi Jan 24 '20 at 17:12
  • @Ivar, I just updated the code and Fiddle : https://jsfiddle.net/Imabot/4mvdn1jf/13/ – Fifi Jan 24 '20 at 17:17
  • @Fifi Your fiddle shows "error" for me. – Ivar Jan 24 '20 at 17:19
  • @Ivar, Yes, I updated the JSFiddle, but have a look at the console. The error is displayed. – Fifi Jan 24 '20 at 17:20
  • Ah, it wasn't clear to me that the ultimate goal was to prevent the error from showing up. I'm afraid that you can't prevent that. That error is logged by the browser when it detect a `4xx`/`5xx` response and it doesn't provide a way to suppress that programmatically. See https://stackoverflow.com/questions/16372271/jquery-ajax-how-to-prevent-404-errors-spam-in-chrome-devtools – Ivar Jan 24 '20 at 17:24
  • OK, this time, this is a duplicate.! – Fifi Jan 24 '20 at 17:26
  • Well, I retracted my last vote and you can only vote once on a question. But I believe that you should be able to close vote it yourself, as you have more than 250 reputation. :) – Ivar Jan 24 '20 at 17:28
  • 1
    Already done ;-) – Fifi Jan 24 '20 at 17:29

0 Answers0