我有以下代碼。這已經存在了。catch這里的每個塊究竟是做什么的。這是處理 ASP.NET Web API 例外的正確方法嗎?如果沒有,我如何以正確的方式處理例外。
注意:CustomServiceException第二個catch塊中的 只是擴展了 Exception 類。
try
{
... I am calling my exteral API here using HttpClient class
}
catch(HttpRequestException ex)
{
Logger.Error("my error message", ex.Message);
}
catch(CustomServiceException)
{
throw;
}
catch (Exception ex)
{
Logger.Error("my error message",ex);
}
uj5u.com熱心網友回復:
嗯,它的作用是:
- 當拋出例外時,它檢查例外是否屬于
HttpRequestException或派生型別。如果這是真的,那么它會記錄錯誤訊息并省略其余的catch塊。 - 當例外不是
HttpRequestException派生型別或派生型別時,它檢查它是否是CustomServiceException派生型別或派生型別。如果這是真的,那么它重新拋出例外(注意throw這里使用的是,它保留了原始例外資料)。 - 當例外不是
HttpRequestException或CustomServiceException(或任何派生型別)時,我們有這個“全域”catch塊,它將捕獲任何例外,記錄錯誤訊息并繼續作業。
uj5u.com熱心網友回復:
您的代碼在概念上是這樣做的:
try
{
//... I am calling my exteral API here using HttpClient class
}
catch (HttpRequestException ex)
{
Logger.Error("my error message", ex.Message);
}
catch (Exception ex) when (ex is not CustomServiceException)
{
Logger.Error("my error message", ex);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350359.html
標籤:C# asp.net-mvc 例外 asp.net-web-api
上一篇:在kotlin中添加到地圖時出現UnsupportedOperationException
下一篇:在哪里放置自定義例外類?
