使用AJAX/JSON处理ASP.NET MVC异常

3

我在控制器中有几个类似的方法:

[HttpPost]
public ActionResult AddEditCommentToInvoice(string invoiceNumber, string comments)
{
    var response = new { success = true, msg = "Comment saved", statusMsg = "Comment saved" };

    try
    {
        var recordsModified = invoiceService.AddCommentsToInvoice(invoiceNumber, comments);
        Log.Info(recordsModified ? "Updated Comment" : "Did not update Comment");

    } catch (Exception ex) {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return Json(new {
            success = false,
            msg = "There is missing field data",
            statusMsg = ex.Message
        }, JsonRequestBehavior.AllowGet);
    }

    return Json(response, JsonRequestBehavior.AllowGet);
}

虽然这段代码能够工作,但我不喜欢这种方法,因为:

  1. try/catch语句很耗费资源
  2. 代码捕获了System.Exception异常
  3. 代码难看

现在我知道我可以使用OnException或HandleError属性。
我还研究了一下ELMAH,这看起来很有前途。

但我仍然希望通过AJAX返回JSON给我的用户,以指示操作是否成功。

所以我的问题是,有没有人使用过这三种方法之一(或者具体使用ELMAH)来通过AJAX返回JSON?


ELMAH只监控和报告未处理的异常,不会修改您的应用程序流程,属性方法是最佳选择。 - KiwiPiet
我也一直在做同样的事情,但我一直很讨厌它。期待看到一个解决方案。这总是我“技术债务”清单上的项目之一。 - kryptonkal
@kryptonkal - 我刚刚发现了这个链接 - http://plainoldstan.blogspot.cz/2012/08/mvc-3-elmah-handle-ajaxjson-action.html - coson
1个回答

2

我使用另一种方法,这种方法可以在控制器级别或通过GlobalFilters全局应用。在我的MVC控制器中,您可以重写OnActionExecuted方法,并执行以下操作:

   protected override void OnActionExecuted(ActionExecutedContext filterContext)
   {
      if (filterContext.Exception != null)
      {
         filterContext.Result = Json(new { success = false });
         return;
      }

      base.OnActionExecuted(filterContext);
   }

这也可以作为一个操作过滤器属性来完成。您不需要在控制器中进行任何异常处理 - 如果发生异常,则在结果的上下文中处理。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接