Find specific DbContext, when handling a SqlExcpetion

261 views Asked by At

I want to create an Exception Filter:

public class BigTouchExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        var sqlException = filterContext.Exception as SqlException;
        if (sqlException == null)
        {
            return;
        }
        //Todo: Handle when it is thrown by `BigTouchContext`
    }
}

I have two different DbContexts: MainContext:DbContext, and BigTouchContext:DbContext. I want to detect in my ExceptionFilter, if the Error is thrown by BigTouchContext (Which are actualy multiple tenants).

Is it possible to override the DbContext in some way, that it transmits the context type via a custom exception?

1

There are 1 answers

2
Athanasios Kataras On BEST ANSWER

I could not really find a way to get the DBContext from the assosciated exception, but I can propose a workaround

  1. Catch the DbUpdateException in your filter.

  2. Now in this exception, you can find the entities that failed by accessing the DbUpdateException.Entries Property

  3. Create two lists of entities in the filter as described here

    var entityTypes = db.Model.GetEntityTypes().Select(t => t.ClrType).ToList();
  1. Get the first entry that failed from step two, and use the GetType() method it exposes to search the types from the two lists. The first one that's got it, is your DBContext of choice.

I have not tried that out, but it looks to me like it's going to work.

Unfortunately, DBContext throws one of the following Check MSDN here. SQL exception for connectivity issues is not related to DBContext and thus, can't be assosciated to one.

You could maybe correlate by the server SQL Exception get server name which could also be in the DBContext connection string