在async方法中,發生一個異常時,代碼並不會直接跳到catch語句中去,而是繼續執行,所以到最后catch語句中得到的錯誤信息是one or more exceptions occurs…
這樣的設計給我們帶來了麻煩就是傳統的try/catch方法得到的無法得到具體的錯誤信息。
【解決方法】
- 在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; } |
- 在 catch語句中取到AggregateException的信息(類似解決方法1),然后重新拋出一個帶有具體錯誤信息的異常給調用者。
- 將異常轉成AggregateException后,可以取到InnerException或者InnerExceptions, 然后再用解決方法1或者2進行處理。