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 ofcatch
blocks. - when the exception is not of
HttpRequestException
or derived type, it checks if it isCustomServiceException
or derived type. If this is true, then it re-throws the exception (note thatthrow
is used here, which preserves original exception data). - when the exception is not of
HttpRequestException
orCustomServiceException
(or any of derived types), then we have this 'global' catch block, which will catch any exceptions, log error message and continue working.