Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify return's statement from try-catch [duplicate]

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?

like image 795
Anatoly Avatar asked Mar 01 '26 17:03

Anatoly


1 Answers

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);
}
like image 134
Patrick Hofman Avatar answered Mar 03 '26 05:03

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!