未捕获异步代码中的实体框架异常

时间:2019-06-11 15:15:48

标签: c# asynchronous exception

我有一个托管在Azure上的服务,该服务将同时在多个实例中运行,它一直是异步调用。在链的深处,有一种将数据保存到数据库的方法。当多个实例试图将相同的数据写入数据库时​​,我有处理异常的代码,但从未捕获到异常。

在Azure上托管的服务

 public async Task Start(CancellationToken cancellationToken = default)
        {

                 // Do something .... 
                await processedInventoryRepository.Commit(invenotyData).ConfigureAwait(false);
        }

存储库将数据保存到数据库

public class Repository
    {
        public async  Task Commit(InventoryData data)
        {
            try
            {
                await SaveHardware(data.Hardware).ConfigureAwait(false); ;
                await SaveProduct(data.Product).ConfigureAwait(false); ;
                await SaveInstall(data.Installs).ConfigureAwait(false); ;
            }
            // Exception handle not handled here 
            catch (DbUpdateException ex)
            {
                var innerException = (SqlException)ex.InnerException;
                if (innerException != null && (innerException.Number == 2627 || innerException.Number == 2601))
                {
                  // log the error;
                }
            }
        }

        private async Task SaveInstall(DbContext _context, Install installs)
        {
            _context.Installs.Add(installs);
            await _context.SaveChangesAsync().ConfigureAwait(false);
        }

        private async Task SaveProduct(DbContext _context, Porduct product)
        {
            try
            {
                if (!_context.Products.Any(p => p.Id == product.Id))
                {
                    _context.Products.Add(product);
                    await _context.SaveChangesAsync().ConfigureAwait(false);
                }

            }
            // Exception not handled here 
            catch (DbUpdateException ex)
            {
                var innerException = (SqlException)ex.InnerException;
                if (innerException != null && (innerException.Number == 2627 || innerException.Number == 2601))
                {
                   // log the error
                }
            }
        }

保存到数据库中的数据没有什么特别的,但是值得一提的是Install具有Product的外键。

该异常发生在SaveProduct方法中,这是预期的,因为多个实例正在争相添加相同的查找。这就是为什么将catch子句放置在此处试图忽略此错误并继续执行的原因。 _context.Produts.Add(product)可以,但是调用SaveChanges时会引发异常。这些捕捉都没有。

很难获得被剥离的代码来复制问题,我在Web api中具有相同的代码,并通过使用邮递员来触发它,因为没有例外,所以它可以工作。但是在Azure中,一旦有多个实例在运行,异常就会一直发生。

例外是可以的,但我只是不知道如何处理它们。预先感谢。

0 个答案:

没有答案
相关问题