Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write multiple exceptions within a method when it is being discouraged in C#?

Tags:

c#

.net

exception

My code just looks like this:

try
{
   foo();
}
catch (SecurityTokenValidationException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
    return null;
}
catch (SignatureVerificationFailedException ex)
{
    Logger.ErrorFormat(ex.Message, ex);
    return null;
}

But the code analysis reports "Avoid Excessive Complexity"

Any pointers ?

like image 381
now he who must not be named. Avatar asked Dec 01 '25 04:12

now he who must not be named.


1 Answers

If you are using C# 6 you can restrict the handling to your two types with exception filtering:

try
{
    foo();
}
catch (Exception ex) when (ex is SecurityTokenValidationException || ex is SignatureVerificationFailedException)
{
    Logger.ErrorFormat(ex.Message, ex);
    return null;
}

So you don't have to potentially catch other sub types of SecurityTokenException by mistake.

like image 147
Stefano d'Antonio Avatar answered Dec 02 '25 17:12

Stefano d'Antonio