0

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?

1 Answer 1

2

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) { }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.