[英]How to handle specific HttpClient errors
當HttpClient
拋出一個試圖獲取頁面的異常時,它會返回一個HttpRequestException
。 除了消息之外,這個異常實際上沒有任何東西可以對錯誤進行分類,所以我可以看到處理錯誤的唯一方法是這樣的:
try
{
HttpResponseMessage response = await client.GetAsync("http://www.example.com/");
// ...
}
catch (HttpRequestException e)
{
if(e.Message == "Name or service not known")
{
HandleNotKnown();
return;
}
if(e.Message == "Some other specific message")
{
HandleOtherError();
return;
}
// ... etc
}
我不喜歡這樣做,因為我覺得在某些時候錯誤文本可能會在更新中更改並破壞我的代碼。
有沒有更好的方法來處理 HttpClient 的特定錯誤?
HttpRequestException繼承自 Exception,因此它具有 InnerException 屬性
Gets the Exception instance that caused the current exception.
因此,請查看此異常以獲取更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.