Search code examples
c#entity-frameworkexception

Catch DbUpdateException and Looks for is UniqueValidationError or not?


I am catching DBUpdateExcdeption. My purpose is checking for is it UNIQUE VALIDATION ERROR or not.

I tried to convert InnerExcdeption to SqlExceptionbut didnt worked.

public static bool IsExceptionUniqueConstraintViolation(Exception ex)
{
    var sqlException = ex.InnerException as SqlException;

    if (sqlException.Number == 2601 || sqlException.Number == 2627)
       return true;

    return false;
}

What is wrong?


Solution

  • The inner exception is most likely not a SqlException so the as conversion will fail (see as operator documentation). When the conversion fails, the result will be null.

    When you have nested exceptions, it's possible that there is more than 1 level of nesting, so you might have a SqlException more than one level down - you can just assume the inner exception will be a SqlException if the exception is thrown by code within a library.

    You also want to add in a check for if the exception really is a SqlException:

    if (ex.InnerException is SqlException)
    {
        var sqlException = (SqlException)ex.InnerException;
    
        if (sqlException.Number == 2601 || sqlException.Number == 2627)
           return true;
    } 
    
    return false;