【发布时间】:2012-05-19 11:23:40
【问题描述】:
我正在寻找在返回 JSON 结果时处理控制器中的错误的最佳方法。
首先,如果我在控制器中遇到未处理的异常并且返回 JSON,那么最佳做法是什么?我在想 400 或 500 错误?客户端检查状态并执行任何操作。
我正在使用 FilterAttribute 和 IExceptionFilter 但我无法调用 OnException 函数。我已将该属性应用于控制器操作。
有什么想法可能不会调用吗?
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class AjaxHandleErrorAttribute : FilterAttribute, IExceptionFilter
{
// This is never called !!!
public void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.Exception != null
&& !filterContext.ExceptionHandled)
{
...
filterContext.HttpContext.Response.StatusCode = 400;
filterContext.HttpContext.Response.StatusDescription = "Error processing request";
...
}
}
}
public class MyController : Controller
{
public MyController(IMyRepository repo)
{
...
}
[AjaxHandleError]
public ActionResult GetSomeJson(int anId)
{
throw new System.Exception();
}
}
【问题讨论】:
标签: asp.net-mvc