Notbad
Notbad

Reputation: 6296

Best way to handle transaction errors?

What's the best way to handle transaction errors in Asp.net core and entity framework?

At this time I have come with something like:

using (var transaction = _dbContext.Database.BeginTransaction())
{
    try
    {
        await _dbContext.MyTable1.AddAsync(table1Entity);
        await _dbContext.SaveChangesAsync();

        Entity2 e2 = new Entity2();
        e2.Table1Id = table1Entity.Id;
        await _dbContext.SaveChangesAsync();
        await transaction.CommitAsync();

        return new CreatedAtRouteResult(...);
    }
    catch (Exception ex)
    {
        System.Console.Write(ex);
        await transaction.RollbackAsync();

        var context = HttpContext.Features.Get<IExceptionHandlerFeature>();

        return Problem(
            detail: context.Error.StackTrace,
            title: context.Error.Message);
    }
}

But don't really know if this is a good practice. How would you do this?

Upvotes: 1

Views: 1268

Answers (2)

sarvasana
sarvasana

Reputation: 757

There is nothing wrong with the way you are handling the transactions, but there are some improvements you can make here:

  1. Remove the data access code from your controller and move it into a separate class.
  2. Do not return the technical details of the error, but a user friendly message.
  3. AddAsync only exists for special use cases, all other cases should use the non-async method Add.

From the EF docs:

"This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used."

Upvotes: 1

vunz
vunz

Reputation: 71

I think your code was good, except you don't need to call:

await transaction.RollbackAsync();

in catch block. Failed transaction will auto-rollback when disposed.

Link: https://learn.microsoft.com/en-us/ef/core/saving/transactions

Upvotes: 1

Related Questions