【问题标题】:catching specific exceptions coming from another Task method捕获来自另一个 Task 方法的特定异常
【发布时间】:2023-04-02 11:43:01
【问题描述】:

我有这两种方法,而且我确信 DoSomethingAsync 返回一个 FormatException。但是它总是在最后一个 catch “Exception”中被捕获

为什么 CallSomethingAsync 永远不会捕获 FormatException?

       public Task DoSomethingAsync()
       {
            //Do something that throws a FormatException 

            return Task.FromResult(0);           
       }

   public virtual string CallSomethingAsync()
   {
        try
        {
            this.DoSomethingAsync().Wait();

            return “Ok”;
        }
        catch (FormatException)
        {
            return “FormatException”;
        }
        catch (Exception)
        {
            return “GeneralException”;
        }
   }

【问题讨论】:

    标签: c# asp.net-mvc exception-handling task


    【解决方案1】:

    因为任务可能返回一个或多个异常,所以它会抛出一个 AggregateException,其中包含任务执行期间发生的所有异常。

    您需要枚举 InnerExceptions 集合以显式处理不同类型的异常。

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2015-11-13
      • 2014-06-21
      相关资源
      最近更新 更多