BVernon
BVernon

Reputation: 3747

How to show .net exception thrown from jquery ajax call?

I'm absolutely certain this has to be a duplicate, but I can't quite find the answer I'm looking for so ideally some kind soul will be able to quickly close this as a duplicate and point me to the answer I'm looking for.

I make an ajax call to a .net MVC action and an exception is thrown. How do I get the message of the exception in the error function of the ajax call?

To be clear, I do not want to catch the exception in .net and then send a message that will be received in the success function. In my first development job this type of approach was taken in an api and it literally cost a grocery store a lot of money because the developer did not read the documentation and implemented the integration incorrectly. Had there been an actual error this would have never happened.

Likewise, this is dealing with payments, and I do not want someone to inadvertently approve an order because they failed to read documentation (of which there will be none in the first place as this is used internally for a small business) and think that because no error was thrown the order must have processed successfully.

Having said that, I'm just looking for the simplest possible way to get the Message property of the exception and display it (the exception itself is not custom, but the message on it will be; so no worry of unanticipated exceptions giving away system details getting through).

EDIT: I realize now what I'm asked for isn't possible. The things I really want though are

a) For the ajax method's error callback to be run (and, of course the success callback not to be run)

b) To be able to access the Message of the exception

Generally an exception is going to send back a 500 response. Is it maybe possible for me to modify the response to put the message on it somewhere that it could be accessed from the error callback?

Upvotes: 0

Views: 674

Answers (1)

DPS
DPS

Reputation: 1003

You can try this out: error:function() will catch the exceptions

 $.ajax({
    url: '',
    type: "",
    data:'',
    beforeSend:function(){
    },
    success: function (data) {
    },
    error: function (jqXHR, exception) {
    var msg = '';
    if (jqXHR.status === 0) {
        msg = 'Not connect.\n Verify Network.';
    } else if (jqXHR.status == 404) {
        msg = 'Requested page not found. [404]';
    } else if (jqXHR.status == 500) {
        msg = 'Internal Server Error [500].';
    } else if (exception === 'parsererror') {
        msg = 'Requested JSON parse failed.';
    } else if (exception === 'timeout') {
        msg = 'Time out error.';
    } else if (exception === 'abort') {
        msg = 'Ajax request aborted.';
    } else {
        msg = 'Uncaught Error.\n' + jqXHR.responseText;
    }
    console.log(msg);
}

Upvotes: 2

Related Questions