How to catch the error thrown by an invalid URL using XMLHttpRequest

和自甴很熟 提交于 2020-01-05 07:04:13

问题


I have not worked much with the XMLHttpRequest object in JavaScript. I am new to it. I have done many jQuery Ajax calls, but have not worked in much detail with the XMLHttpRequest object.

I am working through a book where they give some sample code using this object.

Here is some code the book uses when trying to deal with errors. It is supposed to catch the error thrown by the incorrect URL. But I can't get it to go it the catch clause:

var httpRequest = new XMLHttpRequest();
try
{
     httpRequest.open("GET", "http://");
     httpRequest.send();
}
catch (error)
{
     alert("in catch clause");
}

I have even tried an invalid URL and still doesn't want to go into the catch clause:

httpRequest.open("GET", "gttp://");

Is it because the URL is a valid URL that it is not throwing an exception?


回答1:


var httpRequest = new XMLHttpRequest();
try
{
     httpRequest.open("GET", "http://",false);
     httpRequest.send();
}
catch (error)
{	 
	
     alert("in catch clause");
}

The default open method is asynchronous and cannot be caught in try/catch block. This is because the entire code will get executed even before the open method is completed. open method has got another optional parameter called async which is boolean and default is true. Setting it to false will get the job done. If this value is false, the send() method does not return until the response is received.



来源:https://stackoverflow.com/questions/40337189/how-to-catch-the-error-thrown-by-an-invalid-url-using-xmlhttprequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!