Home > Back-end >  C# Retry Policy: How to check what exception you receive as a variable?
C# Retry Policy: How to check what exception you receive as a variable?

Time:09-06

I have a retry policy created for SQL Exceptions but it seems to not be retrying properly.

I am currently trying to debug and I want to create a temporary code line to test if the exception is a SQL Exception:

if (exception == SQLException) then bool correct = true;

But how would I create an exception variable?

I am currently causing the exception by using RAISERROR('test', 16, 1); in the stored procedures in the database and also creating a SQL timeout.

Just want to check if the exception I'm receiving is a SQL Exception or if it's not even registering.

Thank you

CodePudding user response:

Not sure enough about the context, but if you have the exception object, then try the is operator

if (ExceptionObject is SqlException ) 
{
  //run the retry logic for SqlException 
}

The details are here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast

CodePudding user response:

Just catch the SqlException and check for the Class and State properties:

if (exception is SqlException sqlException) 
{
    if(sqlException.Class == 16 && sqlException.State == 1)
    {
          
    }
}
  • Related