简体   繁体   中英

How to handle specific HttpClient errors

When the HttpClient throws an exception trying to get a page it returns a HttpRequestException . This exception doesn't really have anything to categorize the error apart from the message so the only way i can see to handle errors is like so:

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
}

I don't like doing this because I feel like at some point the error text could change in an update and break my code.

Is there a better way to handle specific errors with HttpClient?

The HttpRequestException inherits from Exception and so it has the InnerException property

在此处输入图像描述

Gets the Exception instance that caused the current exception.

So check this Exception for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM