我正在构建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"
});
}
}
}
对于某些类型的异常,我只想继续从控制器进行处理。但是我该怎么做呢?
通过编写try..catch
您希望此行为发生的位置。请参见在引发并捕获异常后恢复代码执行。
为了澄清,我假设您有这样的东西:
void ProcessEntries(entries)
{
foreach (var entry in entries)
{
ProcessEntry(entry);
}
}
void ProcessEntry(entry)
{
if (foo)
{
throw new EntryProcessingException();
}
}
并且当EntryProcessingException
抛出该异常时,您实际上并不在意并希望继续执行。
如果这个假设是正确的:您将无法使用全局异常过滤器执行此操作,因为一旦捕获到异常,就不会将执行返回到引发该异常的位置。C#中没有On Error Resume Next,尤其是当@Marjan解释使用过滤器处理异常时,尤其如此。
因此,EntryProcessingException
从您的过滤器中删除,并通过更改循环主体来捕获该特定异常:
void ProcessEntries(entries)
{
foreach (var entry in entries)
{
try
{
ProcessEntry(entry);
}
catch (EntryProcessingException ex)
{
// Log the exception
}
}
}
而且,您的循环会很乐意旋转到尽头,但会引发所有其他异常,这些异常将由您的过滤器处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句