c# - 如何在 ASP.NET Web Api 服务中不抛出异常?

标签 c# asp.net .net exception asp.net-web-api

我正在构建 ASP.NET Web Api 服务,我想创建集中式异常处理代码。

我想以不同的方式处理不同类型的异常。我将使用 log4net 记录所有异常。对于某些类型的异常(exception)情况,我想通过电子邮件通知管理员。对于某些类型的异常,我想重新抛出一个更友好的异常,并将其返回给调用者。对于某些类型的异常,我只想继续从 Controller 进行处理。

但是我该怎么做呢?我正在使用异常过滤器属性。我有这个代码工作。该属性已正确注册并且代码正在触发。我只是想知道如果抛出某些类型的异常我该如何继续。希望这是有道理的。

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"
      });
    }
  }
}

最佳答案

For some types of exceptions I want to just continue processing from the controller. But how do I do that?

通过在您希望发生此行为的位置写入 try..catch 。请参阅Resuming execution of code after exception is thrown and caught .

为了澄清,我假设你有这样的东西:

void ProcessEntries(entries)
{
    foreach (var entry in entries)
    {
        ProcessEntry(entry);
    }
}

void ProcessEntry(entry)
{
    if (foo)
    {
        throw new EntryProcessingException();
    }
}

当抛出EntryProcessingException时,你实际上并不关心并希望继续执行。


如果这个假设是正确的:你不能使用全局异常过滤器来做到这一点,因为一旦捕获到异常,就不会返回到抛出异常的位置。 There is no On Error Resume Next在 C# 中,尤其是当使用过滤器处理异常时 @Marjan explained .

因此,从过滤器中删除 EntryProcessingException,并通过更改循环体捕获该特定异常:

void ProcessEntries(entries)
{
    foreach (var entry in entries)
    {
        try
        {
            ProcessEntry(entry);
        }
        catch (EntryProcessingException ex)
        {
            // Log the exception
        }
    }
}

您的循环将愉快地旋转到结束,但会抛出所有其他异常,其中它将由您的过滤器处理。

关于c# - 如何在 ASP.NET Web Api 服务中不抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662469/

相关文章:

c# - 带有 NetTcpBinding 的 WCF 服务库

c# - 如何关闭网络浏览器控件中的查找窗口

c# - AjaxControlToolkit.MaskedEditExtender 错误

c# - SqlDataAdapter.Fill(DataTable) 未填充 DataTable

c# - 从泛型类获取 ICollection 类型属性的列表

.net - 如何在 WPF 类库上使用 .NET Framework 4.8?

c# - 从 RadGrid 中删除编辑、更新和取消链接

c# - System.DateTime.Now 在 C# 中返回什么?

c# - DataContractJsonSerializer 的静态实例 - 好的还是坏的设计?

asp.net - 模拟 ASP.NET 将身份声明为 Windows 身份