If a normal page load errors I can report the exception details to the user via the Error view and HandleErrorInfo model.
If an ajax call expecting a Json result errors, I can explicitly handle the error and pass details to the client:
public JsonResult Whatever()
{
try
{
DoSomething();
return Json(new { status = "OK" });
}
catch (Exception e)
{
return Json(new { status = "Error", message = e.Message });
}
}
So, my problem, I can’t see any way to report error details from an Ajax call to an action returning a partial view.
$.ajax({
url: 'whatever/trevor',
error: function (jqXHR, status, error) {
alert('An error occured: ' + error);
},
success: function (html) {
$container.html(html);
}
});
This will only report an Http error code (e.g. Internal Server Error) which is not helpful to the client. Is there some clever trick to pass either a successful PartialView (html) result or an error message?
Explicitly evaluating the html from the ViewResult and returning it as part of a Json object along with a status seems too smelly. Is there an established pattern for handling this scenario?
Controller action:
Then we define a Global error handler for our application:
Here’s how the ErrorsController used in the global error handler could look like. Probably we could define some custom views for the 404 and 500 actions:
Then we could subscribe for a global error handler for all AJAX errors so that we don’t have to repeat this error handling code for all AJAX requests but if we wanted we could repeat it:
And finally we fire an AJAX request to the controller action that we hope will return an HTML partial in this case: