Home > Enterprise >  exception handling with http client - c#
exception handling with http client - c#

Time:11-05

I have the following code. This already exists. What exactly is each block of catch doing here. Is this the correct way of handling exceptions on ASP.NET Web API? If not, how can I handle exceptions the correct way.

Note: The CustomServiceException in the second catch block simply extends the Exception class.

        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);
        }

CodePudding user response:

Your code is conceptually doing this:

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);
}

CodePudding user response:

Well, what it does is:

  • when exception is thrown, it checks if the exception is of HttpRequestException or derived type. If that is true, then it logs error message and omits rest of catch blocks.
  • when the exception is not of HttpRequestException or derived type, it checks if it is CustomServiceException or derived type. If this is true, then it re-throws the exception (note that throw is used here, which preserves original exception data).
  • when the exception is not of HttpRequestException or CustomServiceException (or any of derived types), then we have this 'global' catch block, which will catch any exceptions, log error message and continue working.
  • Related