在async方法中,发生一个异常时,代码并不会直接跳到catch语句中去,而是继续执行,所以到最后catch语句中得到的错误信息是one or more exceptions occurs…

这样的设计给我们带来了麻烦就是传统的try/catch方法得到的无法得到具体的错误信息。

 

【解决方法】

  1. 在catch语句中记录错误信息

if (e is AggregateException)

{

AggregateException ae = (AggregateException)e;

ae.Handle((x) =>

{

exception = x.Message;

return true; // Let anything else stop the application.

});

}

else

{

exception = e.Message;

}

 

  1. 在 catch语句中取到AggregateException的信息(类似解决方法1),然后重新抛出一个带有具体错误信息的异常给调用者。
  2. 将异常转成AggregateException后,可以取到InnerException或者InnerExceptions, 然后再用解决方法1或者2进行处理。
posted on 2016-12-07 16:56  今夜太冷  阅读(5665)  评论(0编辑  收藏  举报