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