【发布时间】:2013-11-08 20:36:40
【问题描述】:
我正在构建一个 ASP.NET Web Api 服务,我想创建集中的异常处理代码。
我想以不同的方式处理不同类型的异常。我将使用 log4net 记录所有异常。对于某些类型的例外情况,我想通过电子邮件通知管理员。对于某些类型的异常,我想重新抛出一个更友好的异常,该异常将返回给调用者。对于某些类型的异常,我只想继续从控制器处理。
但是我该怎么做呢?我正在使用异常过滤器属性。我有这个代码工作。该属性已正确注册并且代码正在触发。我只想知道如果抛出某些类型的异常,我该如何继续。希望这是有道理的。
public class MyExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
//Log all errors
_log.Error(myException);
if(myException is [one of the types I need to notify about])
{
...send out notification email
}
if(myException is [one of the types that we continue processing])
{
...don't do anything, return back to the caller and continue
...Not sure how to do this. How do I basically not do anything here?
}
if(myException is [one of the types where we rethrow])
{
throw new HttpResponseException(new HttpResponseMessage(StatusCode.InternalServerError)
{
Content = new StringContent("Friendly message goes here."),
ReasonPhrase = "Critical Exception"
});
}
}
}
【问题讨论】:
-
异常过滤器仅在 WebAPI 消息管道的“返回”部分触发。因此,如果您依靠异常过滤器来处理您的异常,我认为没有一种简单的方法可以让请求重新进入管道以进行进一步处理。有关 WebAPI 扩展点的更多信息,请参阅MVC Poster。
标签: c# asp.net .net exception-handling asp.net-web-api