Search code examples
c#exceptionentity-framework-4.1

entity framework 4.4: how to catch the Sql Exception?


I have a table in the database that has the users of the application. The user name is unique, so I have a unique constraint in the table.

I am doing probes and one is try to use the same user name for two users. When the error occurs, I catch the exception "Eception" and I can see that the catched exception is System.Data.Entity.Infraestructure.DbUpdateConcurrencyException and the inner exception is System.Data.OptimisticConcurrencyException.

Then I catch the DbUpdateConcurrencyException, the innter exception is the OptimisticConcurrencyException, so I try to catch this exception too.

If I try to catch the OptimisticConcurrencyException before the DbUpdateConcurrencyException, is not catch, is catch the DbUpdateConcurrencyException.

SO I don't know how I can to catch the SqlException, because I would like to catch the error of the Sql Server, to get the code.

Thanks.


Solution

  • You can't handle 'inner exceptions'. You need to inspect the actual exception thrown in your catch handler, and rethow if you can't handle it. Example:

    try
    {
    }
    catch (DbUpdateConcurrencyException ex)
    {
       if (CanHandleException(ex)) 
       {
           // do what you have to do to handle the exception
       }
       else
       {
           throw; // can't handle this exception - just let it bubble up
       }
    }
    

    In the method CanHandleException you would write the logic that determines whether you can handle this exception and do something meaningful (perhaps retry the operation). You do this by inspecting the properties of the exception (message, InnerException, ...)