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