Hi guys I've noticed that at times exceptions do get thrown on server sided code - however when it comes to ajax requests how do I implement it such that I'm able to inform the user that an exception has been thrown and something has gone wrong? I'm using Php on the back end here.
It depends on what does the AJAX method return. If it is plain HTML, you could output an error message instead, which will be presented to the user. If it is JSON, then add some fields to the structure, which can hold an error message or error code, so you can handle it when you retrieve the response client side.
Your ajax request can respond with a server code of 500 alerting the AJAX caller that something went horribly wrong. Most libraries implement an onFailure callback that will be triggered in this event.
I don't know if you use jQuery or not. My answer is given assuming you use jQuery, but you can apply the same concept to another JavaScript framework (or none). In this way, the users would actually be looking at the stack trace instead of a generic error message (which is uselss anyway):
$.ajax({
url: '/some_url',
type: 'post', //or get
data: ...,
success: function() { /* handle success */ },
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#error_dlg').dialog('open').trigger('initDlg', [XMLHttpRequest]);
}
});
$('#error_dlg').dialog({
autoOpen: false,
width: 550,
height: 400,
modal: true,
buttons: {
'Close': function() {
$(this).dialog('close');
}
},
open: function(event, ui) {
}
}).bind('initDlg', function(e, XMLHttpRequest) {
$('#error_stack_trace').append($('<div>').html(XMLHttpRequest.responseText));
});
Something I ran into recently that might be helpful is this:
http://php.net/manual/en/function.set-error-handler.php
Basically, if PHP runs into an error, it will use your handler, which you can design to work with an asynchronous request or a synchronous request.
However, it seems that you are also throwing exceptions within your code. From a cursory glance, you can create a custom Exception handling class as well.
http://www.w3schools.com/php/php_exception.asp
Once again, you can design it to work with asynchronous or synchronous requests. In your Javascript, if you are using JSON as a response, you can simply set an error flag that will alert your code of an exception/error and it will respond appropriately. If you're using straight HTML as a response, you might have to send a 500 error (or one of the other variants, I'm not well versed in the 500 codes) so that you can use the onFailure
or failure
function handlers as others have mentioned.