ASP.NET MVC Ajax错误返回视图而不是ajax

Ada*_*itt 4 ajax error-handling asp.net-mvc jquery

我正在通过AJAX对一个方法进行ASP.NET MVC调用,错误会引发异常.我希望将异常的消息传递回客户端,我宁愿不必捕获异常.像这样的东西:

[HttpPost]
public ActionResult AddUser(User user) {
  if (UserIsValid(user)) {
    return Json(new { resultText = "Success!" });
  } 
  throw new Exception("The user was invalid.  Please fill out the entire form.");
}
Run Code Online (Sandbox Code Playgroud)

我在我的firebug响应中看到一个HTML页面

<!DOCTYPE html>
<html>
    <head>
        <title>"The user was invalid.  Please fill out the entire form."</title>
        .....
Run Code Online (Sandbox Code Playgroud)

我不想被迫使用try catch块来执行此操作.有没有办法自动获取jQuery $(document).ajaxError(function(){}来读取此异常消息?这是不好的做法?我可以覆盖控制器OnException吗?或者我是否必须尝试/ catch并返回JSON?

像这样的东西会很好:

$(document).ajaxError(function (data) {
    alert(data.title);        
});
Run Code Online (Sandbox Code Playgroud)

Fra*_*cis 8

您可以使用自定义过滤器执行此操作:

$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});
Run Code Online (Sandbox Code Playgroud)

-

[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
    if (isTrue)
    {
        return Json(new { Foo = "Bar" });
    }
    throw new HttpException(404, "Oh noes...");
}

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        var statusCode = new HttpException(null, exception).GetHttpCode();

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
            Data = new
            {
                error = true,
                message = filterContext.Exception.Message
            }
        };

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = statusCode;  
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

有点受到这篇博文的启发:http://www.prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc