Alex
Alex

Reputation: 9429

.net MVC handle view compilation error loaded by ajax

I have a view with a compilation error. This view gets loaded via an ajax call. I would like to return the compilation error message as a simple string message, but MVC is returning an entire HTML page as an error.

I have an ajax error handler that looks for the error message in request.responseText, like this:

$(document).ajaxError(function (event, request, settings) {
    ....
    //contains html error page, but I need a simple error message
    request.responseText 
    ....
});

How can I return a simple error message to the ajax error handler when there is a view compilation error?

Upvotes: 0

Views: 370

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could write a global exception handler in Global.asax that will intercept errors occurin during an AJAX request and serialize them as a JSON object to the response so that your client error callback could extract the necessary information:

protected void Application_Error(object sender, EventArgs e)
{
    if (new HttpRequestWrapper(Request).IsAjaxRequest())
    {
        var exception = Server.GetLastError();
        Response.Clear();
        Server.ClearError();
        Response.ContentType = "application/json";
        var json = new JavaScriptSerializer().Serialize(new
        {
            // TODO: include the information about the error that
            // you are interested in => you could also test for 
            // different types of exceptions in order to retrieve some info
            message = exception.Message
        });
        Response.StatusCode = 500;
        Response.Write(json);
    }
}

and then:

$(document).ajaxError(function (event, request, settings) {
    try {
        var obj = $.parseJSON(request.responseText);
        alert(obj.message);
    } catch(e) { }
});

Upvotes: 2

Related Questions