tvanfosson
tvanfosson

Reputation: 532435

How do I get the exception message from a failed jQuery request?

If I use jQuery ajax with an error handler and the ASP.NET MVC action that I'm invoking throws an exception, I'd like to be able to display the message in the exception to the user. Right now I'm using:

 $.ajax( {
    ...
    error: function(request,status,error) {
        var exp = new RegExp('<title>(.*)<\/title>','i');
        if (exp.exec(request.responseText)) {
           alert( RegExp.lastParen );
        }
        else {
           alert( status );
        }
    }
 });

I'm hoping for a canonical jQuery implementation, rather than rolling my own.

Upvotes: 1

Views: 778

Answers (3)

Frank Krueger
Frank Krueger

Reputation: 70983

You're looking for something easier than 5 lines of code? Really?

Line 1, parse the error. This is custom to your server so I don't see how any generic facility of jQuery could help.

Lines 2-5, show different errors based upon the parse. Again, this is custom to your server.

I personally wouldn't use an anonymous function here (call it alertUser or something), but I see nothing wrong with this approach.

Upvotes: 0

Chad Grant
Chad Grant

Reputation: 45382

Nothing wrong with what you're doing but if you want ideas ... what about a custom error page that would serialize the error as JSON if the request has application/json header?

Upvotes: 1

Portman
Portman

Reputation: 31975

For what it's worth, I usually have any action that returns a JsonResult wrapped in a try/catch block so that it cannot throw an exception. Instead, I return two parameters with every Json array: "ok" (true/false) and "message" (containing the message to display to the user if there is an error).

Then I omit the $.ajax "error" parameter, and do a simple branch on the "ok" parameter of the JsonResult result.

Upvotes: 3

Related Questions