Discussion: an alternative approach to ensuring consistent exception handling (#129)

Catch exception types expected on Linux and handle gracefully
This commit is contained in:
Bevan Arps 2019-01-25 14:56:09 +13:00 коммит произвёл peterbom
Родитель cc0892da56
Коммит cfefa72afd
1 изменённых файлов: 23 добавлений и 6 удалений

Просмотреть файл

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.Azure.Batch.SoftwareEntitlement.Common
@ -83,6 +84,8 @@ namespace Microsoft.Azure.Batch.SoftwareEntitlement.Common
/// <param name="storeLocation">Location within the store to check.</param>
/// <returns>Sequence of certificates (possibly empty).</returns>
private static IList<X509Certificate2> FindAll(StoreName storeName, StoreLocation storeLocation)
{
try
{
using (var store = new X509Store(storeName, storeLocation))
{
@ -91,6 +94,12 @@ namespace Microsoft.Azure.Batch.SoftwareEntitlement.Common
return found;
}
}
catch (Exception ex) when (IsExpectedOnLinux(ex))
{
// Some store locations not supported on Linux, just return null
return new List<X509Certificate2>();
}
}
/// <summary>
/// Find a certificate based on the provided thumbprint
@ -145,13 +154,21 @@ namespace Microsoft.Azure.Batch.SoftwareEntitlement.Common
var found = store.Certificates.Find(thumbprint);
return found.SingleOrDefault();
}
}
catch (PlatformNotSupportedException)
catch (Exception ex) when (IsExpectedOnLinux(ex))
{
// Some store locations not supported on Linux, just return null
return null;
}
}
/// <summary>
/// Test to see if a given exception is one we expect to encounter when running on Linux
/// </summary>
/// <param name="ex">The exception to test.</param>
/// <returns>True if expected; false otherwise.</returns>
private static bool IsExpectedOnLinux(Exception ex)
=> ex is PlatformNotSupportedException
|| ex is CryptographicException;
}
}