Я пытаюсь передать пользовательскую ошибку с контроллера mvc4 asp.net на вызов jquery.ajax(). Поэтому я написал собственный фильтр ошибок:
public class FormatExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult()
{
ContentType = "application/json",
Data = new
{
name = filterContext.Exception.GetType().Name,
message = filterContext.Exception.Message,
callstack = filterContext.Exception.StackTrace
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
else
{
base.OnException(filterContext);
}
}
}
И я зарегистрировал его как глобальный фильтр, выполнив:
GlobalFilters.Filters.Add(new FormatExceptionAttribute());
Ниже моего вызова ajax, определенного в моем представлении mvc4 (обратите внимание, что задача представляет собой строку типа "/MyController/MyAction/"):
function loadData(task) {
ajax({
url: task,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8"
}).then(function (data) {
$(data).map(function (i, item) {
addNewElement(item);
})
},
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');
}
});
};
Поэтому MyAction в Mycontroller выглядит следующим образом:
[HttpPost]
public ActionResult MyAction()
{
try
{
var dataCollection = (dynamic)null;
using (ConfigContext context = new ConfigContext())
{
dataCollection = context.MyItems.Where(i=> i.TypeId == 1).AsEnumerable().OrderBy(k => k.Name).Select(w => new
{
Alias = string.Format("{0}-{1}", Resources.Constants.Prefix, w.Id),
Name = w.Name,
Desc = w.Desc
}).ToArray();
}
return Json(dataCollection);
}
catch (Exception ex)
{
// I want to return ex.Message to the jquery.ajax() call
JsonResult jsonOutput = Json(
new
{
reply = new
{
status = "Failed in MyAction.",
message = "Error: " + ex.Message
}
});
return jsonOutput;
}
}
По какой-то причине в вызове jquery.ajax() я не получаю сообщение ex.message, отправленное контроллером (на стороне сервера) и в jquery.ajax() при попытке конвертировать в json, используя:
var json = $.parseJSON(xhr.responseText);
возникает исключение, говорящее, что это не результат json, поэтому в jquery.ajax входит в тело catch:
} catch (e) {
alert('something bad happened');
}
Итак, я бы хотел:
[HttpPost]
public ActionResult UpdateUser(UserInformation model){
if (!UserIsAuthorized())
return new HttpStatusCodeResult(401, "Custom Error Message 1"); // Unauthorized
if (!model.IsValid)
return new HttpStatusCodeResult(400, "Custom Error Message 2"); // Bad Request
// etc.
}
$.ajax({
type: "POST",
url: "/mymvccontroller/UpdateUser",
data: $('#myform').serialize(),
error: function (xhr, status, error) {
console.log(error); //should be you custom error message
},
success: function (data) {
}
});