TheGateKeeper
TheGateKeeper

Reputation: 4520

Unhandled exceptions during AJAX

I am trying to implement some sort of handler for unhanded exceptions that occur during AJAX but since I am new I can't seem to get the hang of it. What I have experienced on my test setup is that nothing is returned to the client when an exception occurs. Also, none of these exceptions are being handled by ELMAH.

So this questions has 2 parts:

  1. How do I get the server to send back something meaningful, like an error code and message, so that the client can be informed.
  2. How can I get ELMAH to log exceptions that happen during an AJAX callback?

Thanks.

Upvotes: 0

Views: 581

Answers (2)

Rab
Rab

Reputation: 35572

$.ajax({
    type: "post", url: "/SomeController/SomeAction",
    success: function (data, text) {
        //...
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

Or a generic handler

$(function() {
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
});

Upvotes: 1

Jon
Jon

Reputation: 40032

Could you not do a try/catch around your server side code and then pass something meaningful back so the client can output the helpful error message?

I'm not sure why ELMAH is not logging your uncaught exception if its occuring server side though. Are you sure its trapping other errors?

Upvotes: 1

Related Questions