问题
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