将自定义错误从mvc控制器返回到jquery ajax调用
我试图做的是将一个自定义错误从asp.net mvc4控制器传递给jquery.ajax()调用。因此,我编写了一个自定义错误过滤器:将自定义错误从mvc控制器返回到jquery ajax调用,jquery,asp.net-mvc,asp.net-mvc-4,Jquery,Asp.net Mvc,Asp.net Mvc 4,我试图做的是将一个自定义错误从asp.net mvc4控制器传递给jquery.ajax()调用。因此,我编写了一个自定义错误过滤器: public class FormatExceptionAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (filterContext.RequestContext.Htt
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());
下面是在mvc4视图中定义的ajax调用(请注意,任务是一个类似“/MyController/MyAction/”的字符串):
因此,Mycontroller中的MyAction如下所示:
[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()调用中,我没有收到控制器(服务器端)和jquery.ajax()在尝试使用以下命令转换为json时发送的ex.message错误:
var json = $.parseJSON(xhr.responseText);
抛出一个异常,表示它不是json结果,因此jquery.ajax在catch body中输入:
} catch (e) {
alert('something bad happened');
}
所以我想做的是:
} 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) {
}
});