4

我正在通过 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.");
}

我在我的萤火虫响应中看到一个 HTML 页面

<!DOCTYPE html>
<html>
    <head>
        <title>"The user was invalid.  Please fill out the entire form."</title>
        .....

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

像这样的东西会很好:

$(document).ajaxError(function (data) {
    alert(data.title);        
});
4

2 回答 2

8

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

$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});

-

[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;
    }
}

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

于 2013-10-29T22:48:10.437 回答
0

与其处理服务器引发的异常,不如在 JSON 响应中添加一个标志?

[HttpPost]
public ActionResult AddUser(User user) {
  if (UserIsValid(user)) {
    return Json(new { success = true, resultText = "Success!" });
  } 

  return Json(new { success = false, resultText = "The user was invalid.  Please fill out the entire form." });
}
于 2013-10-29T19:29:39.100 回答