【发布时间】:2013-05-02 18:11:11
【问题描述】:
在 ASP.NET Web API 中有什么方法可以将异常标记为在 ExceptionFilterAttribute 中处理?
我想使用异常过滤器在方法级别处理异常,并停止传播到全局注册的异常过滤器。
用于控制器动作的过滤器:
public class MethodExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(context.Exception.Message)
};
// here in MVC you could set context.ExceptionHandled = true;
}
}
}
全局注册的过滤器:
public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is SomeOtherException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.SomethingElse)
{
Content = new StringContent(context.Exception.Message)
};
}
}
}
【问题讨论】:
-
能否请您放一个“使用异常过滤器在方法级别处理异常”的示例?
-
为了进入全局过滤器,我认为首先必须在方法中处理异常 - 那么为什么不将不安全的代码包装在
try/catch块中并在那里处理呢?