Skip to content

Commit

Permalink
Refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
Giorgi committed Aug 6, 2024
1 parent 0e12953 commit 0ef36f1
Showing 1 changed file with 17 additions and 23 deletions.
40 changes: 17 additions & 23 deletions EntityFramework.Exceptions.Common/ExceptionProcessorInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,46 +29,40 @@ protected internal enum DatabaseError
/// <inheritdoc />
public override void SaveChangesFailed(DbContextErrorEventData eventData)
{
var dbUpdateException = eventData.Exception as DbUpdateException;

ProcessException(eventData, dbUpdateException);
ProcessException(eventData, eventData.Exception as DbUpdateException);

base.SaveChangesFailed(eventData);
}

/// <inheritdoc />
public override Task SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken = new CancellationToken())
{
var dbUpdateException = eventData.Exception as DbUpdateException;

ProcessException(eventData, dbUpdateException);
ProcessException(eventData, eventData.Exception as DbUpdateException);

return base.SaveChangesFailedAsync(eventData, cancellationToken);
}

[StackTraceHidden]
private void ProcessException(DbContextErrorEventData eventData, DbUpdateException dbUpdateException)
{
if (eventData.Exception.GetBaseException() is T providerException)
{
var error = GetDatabaseError(providerException);
if (dbUpdateException == null || eventData.Exception.GetBaseException() is not T providerException) return;

var error = GetDatabaseError(providerException);

if (error != null && dbUpdateException != null)
{
var exception = ExceptionFactory.Create(error.Value, dbUpdateException, dbUpdateException.Entries);
if (error == null) return;

var exception = ExceptionFactory.Create(error.Value, dbUpdateException, dbUpdateException.Entries);

switch (exception)
{
case UniqueConstraintException uniqueConstraint when eventData.Context != null:
SetConstraintDetails(eventData.Context, uniqueConstraint, providerException);
break;
case ReferenceConstraintException referenceConstraint when eventData.Context != null:
SetConstraintDetails(eventData.Context, referenceConstraint, providerException);
break;
}
throw exception;
}
switch (exception)
{
case UniqueConstraintException uniqueConstraint when eventData.Context != null:
SetConstraintDetails(eventData.Context, uniqueConstraint, providerException);
break;
case ReferenceConstraintException referenceConstraint when eventData.Context != null:
SetConstraintDetails(eventData.Context, referenceConstraint, providerException);
break;
}
throw exception;
}

private void SetConstraintDetails(DbContext context, UniqueConstraintException exception, Exception providerException)
Expand Down

0 comments on commit 0ef36f1

Please sign in to comment.