Ответ 1
Вы можете написать собственный фильтр ошибок:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new
{
// obviously here you could include whatever information you want about the exception
// for example if you have some custom exceptions you could test
// the type of the actual exception and extract additional data
// For the sake of simplicity let suppose that we want to
// send only the exception message to the client
errorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
а затем зарегистрировать его как глобальный фильтр или применить только к определенным контроллерам/действиям, которые вы собираетесь использовать с AJAX.
И на клиенте:
$.ajax({
type: "POST",
url: "@Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
},
error: function(xhr) {
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch(e) {
alert('something bad happened');
}
}
});
Очевидно, вам было бы скучно писать повторяющийся код обработки ошибок для каждого запроса AJAX, поэтому было бы лучше написать его один раз для всех запросов AJAX на вашей странице:
$(document).ajaxError(function (evt, xhr) {
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('something bad happened');
}
});
а затем:
$.ajax({
type: "POST",
url: "@Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
}
});
Еще одна возможность - адаптировать глобальный обработчик исключений, который я представил, чтобы внутри ErrorController вы проверяли, был ли он запросом AJAX, и просто возвращают детали исключения как JSON.