Catching an error like that will only catch a JavaScript error. That's not what you're experiencing here. Your server is returning a status code of 500
. You need to make sure that everything is good BEFORE you send your users there.
To do that you could effectively 'ping' the URL with Ajax to ensure that it won't 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 would do a HEAD request to the URL to ensure that there are no nasty server errors waiting.
Of course, if in the process of actually GENERATING the CSV your server throws an error - it would still return a 500.
A more robust way would be to get the data via Ajax, build a data URL via base64encode
and then set window.location.href
to that data URL.
By doing that, you could also ensure that the Ajax didn't return a 500 and you got the data you were expecting in the response.
Hope this helps!