处理作为参数传递给函数的Action引发的异常的方法

时间:2019-11-11 11:09:18

标签: c# asp.net-core async-await

  try
    {
        if (productDto.Images != null)
        {
            productDto.ImagesUrls = new List<string>();
            foreach (var image in productDto.Images)
            {
                var name = await _imageWriter.UploadImage(image);
                productDto.ImagesUrls.Add(name);
            }

            await _repository.RemoveProductImages(productDto.Id);
            await _repository.SetNewImagesPathsForProduct(productDto.Id, productDto.ImagesUrls);
        }

        var result =  await base.UpdateAsync(productDto, commands, async (ProductDto dto, bool name) =>
                await CustomValidationWithUserRole(productDto, true));
        return result;
    }
    catch (Exception ex)
    {
        foreach (var imagePath in productDto.ImagesUrls)
            await _imageWriter.RemoveFile(imagePath);

        var oldImageUrls = productDto.ImagesUrls;

        await _repository.SetNewImagesPathsForProduct(productFromDb.Id, oldImageUrls);

        throw;
    }

根据代码片段,我传递了一个返回void的Function,但当模型属性之一无效或db中不存在某些实体时,它会引发异常(验证)。

当此方法(CustomValidationWithUserRole)引发异常时,会发生问题。在try-catch语句中没有被捕获。

如何捕获此异常并将其进一步传递给控制器​​(位于上一层)?

以下是我调用此功能的地方:

    public async Task<UDto> UpdateAsync(UDto dto, List<Command> commands = null, Action<UDto, bool> customDtoEntityValidation = null)
    {
        var updatedModel = default(TModel);

        try
        {
            await DtoSingleValidate(dto, customDtoEntityValidation, true);
            var model = await ConvertDtoToModel(dto);
            updatedModel = await _repository.UpdateAsync(model);
            var updatedDto = await ConvertModelToDto(updatedModel);

            SetIds(commands, updatedDto);
            await SendCommands(commands);
            return updatedDto;
        }
        catch (Exception ex)
        {
            if (updatedModel != default(TModel))
            {
                await _repository.DeleteAsync(updatedModel);
            }
            throw;
        }
    }

    private async Task DtoSingleValidate(UDto dto, Action<UDto, bool> customDtoEntityValidation, bool update)
    {
        if (customDtoEntityValidation == null)
        {
            await DtoValidation(dto, update);
        }
        else
        {
            customDtoEntityValidation.Invoke(dto, update);
        }
    }

1 个答案:

答案 0 :(得分:2)

之所以会这样,是因为您传递的Action是异步的,没有什么等待结果。该操作被执行为“忘却之火”,因为调用者已经继续前进,所以没有任何东西可以捕获异常。

您需要将customDtoEntityValidation的类型更改为Func<UDto, bool, Task>,并await适当地更改结果。

相关问题