3

How can I simplify the following code:

try
{
    var metadata = GetMetadata();
    return metadata ?? _provider.GetLatestMetadata(guid);
}
catch (AuthenticationException)
{
    return _provider.GetLatestMetadata(guid);
}
catch (HttpUnauthorizedRequestException)
{
    return _provider.GetLatestMetadata(guid);
}
catch (WebException)
{
    return _provider.GetLatestMetadata(guid);
}
catch (VcenterException)
{
    return _provider.GetLatestMetadata(guid);
}

I would like to avoid code duplication.

Is it possible?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Anatoly
  • 1,908
  • 4
  • 25
  • 47

1 Answers1

7

If you don't want to do a catch-all and really need to avoid duplicate code, you can catch the specific exceptions with an exception filter:

try
{
    var metadata = GetMetadata();
    return metadata ?? _provider.GetLatestMetadata(guid);
}
catch (Exception ex) when ( ex is AuthenticationException
                            || ex is HttpUnauthorizedRequestException
                            || ex is WebException
                            || ex is VcenterException
                          )
{
    return _provider.GetLatestMetadata(guid);
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325