views:

368

answers:

3

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.

+3  A: 

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.

Portman
+1 I had thought of this, too, but it sort of redefines the meaning of "success" doesn't it?
tvanfosson
I also do something similar, I feel it allows me to do my logging and keep some control over how and what gets displayed to the user.
michaeldelorenzo
+1  A: 

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?

Chad Grant
Can you think of a way to do this without actually catching and consuming the exception? In my case these are truly exceptional conditions and I'd like to have them bubble up so that they are logged.
tvanfosson
I don't know your app logging setup but you can maybe setup Application_Error handler in Global.asax ... catch(Exception ex) { if (json header) { write out json error } else { throw; } ... or Log(ex); and dont re-throw (or you might get double errors ) but again, don't know your error logging setup
Chad Grant
Not quite there yet, but I'm planning to use ELMAH.
tvanfosson
A: 

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.

Frank Krueger
I was hoping that someone knew of a place where jQuery had already hidden the text of the exception away and I had just missed it.
tvanfosson
Actually what would be nice is if jQuery would find it for me and stuff the text into the error parameter, but it looks as if that's only used for client-side errors.
tvanfosson