Javascript: how to catch an error on a page related to using window.location.href = url

I use the REST service to create a CSV file that I want to prompt the user to download. An example service is shown below:

https://localhost:8444/websvc/exportCSV?viewId=93282392

To request the user to download the file, I use this code:

window.location.href = exportUrl , where exportUrl will be a URL similar to the one above.

This works fine if there are no errors on the server while running the service. A prompt appears to download the file, the page will not refresh, and everything will be fine.

However, if the error , I get a nasty 500 HTTP status page, which is not suitable for users. What I would like to do is to catch any error on the final page and cause a more friendly error without leaving the current page. I tried:

 try { window.location.href = exportUrl; } catch (e) { alert(e); } 

But this does not change the behavior at all. Anyone have any ideas on how to handle this?

Many thanks.

+7
javascript window.location try-catch error-handling
source share
1 answer

Catching an error similar to this error will only be a JavaScript error. This is not what you are experiencing here. The server returns a status code of 500 . You must make sure that everything is fine before you send your users.

To do this, you can effectively ping the URL using Ajax to ensure that it does not return a 500 error.

Something like the following:

 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { window.location.href = exportUrl; } } xhr.open('head',exportUrl); xhr.send(null); 

This will result in a HEAD request to the URL to ensure that there are no unpleasant server errors pending.

Of course, if your server generates an error during the actual CSV generation process, it will still return 500.

A more reliable way would be to get the data via Ajax, create the data base64encode through base64encode , and then set window.location.href to that data url.

That way, you can also make sure that Ajax did not return 500, and you got the data expected in response.

Hope this helps!

+2
source share

All Articles