【问题标题】:How do i catch or throw an exception in asp.net core?我如何在 asp.net 核心中捕获或抛出异常?
【发布时间】:2021-07-24 18:46:21
【问题描述】:

我有点不确定在哪里捕获应用程序和任何其他意外异常,但我确实想在前端显示应用程序或任何其他异常发生的异常。

如果我只是从服务管理器中“抛出”,那么它将被控制器捕获,但如果服务管理器和控制器中出现异常怎么办?

这似乎也很冗长。

这是我正在调用 API 的服务管理器。

   public async Task<int> CreateCategory(CategoryViewModel model)
    {
        logger.LogInformation("In {service}, Creating {CategoryModel}", nameof(CategoryServiceManager), model.ToString());

        try
        {
            model.Guard(model.ToString());

            int categoryId = await apiClient.PostAsync<int, CategoryViewModel>("Category", model);

            return categoryId;

        }
        // Guard wil throw
        catch (ApplicationException ex)
        {
            logger.LogError("Exception thrown for {model}: {Message}, {Stacktrace}", model.ToString(),ex.Message, ex.StackTrace);

            throw new ApplicationException($"Exception thrown in service when creating category: {ex.Message}");
        }
        catch (Exception ex)
        {
            logger.LogError("Unexpected error thrown in service when creating a category : {Message}, {Stacktrace}", ex.Message, ex.StackTrace);

            throw new Exception("Unexpected error thrown in service when creating a category");
        }
    }

这是服务管理器中使用的 Guard 扩展。

public static class GuardExtensions
{
    public static void Guard(this string input, string inputName)
    {
        if (string.IsNullOrEmpty(input))
        {
            throw new ApplicationException($"{inputName} must be provided");
        }
    }

    public static void Guard(this object input, string inputType)
    {
        if (input == null)
        {
            throw new ApplicationException($"{inputType} must be provided");
        }
    }
}

这是我使用服务管理器的控制器。

   public async Task<IActionResult> Create(CategoryViewModel model)
    {
        logger.LogInformation("In {controller}, Creating {CategoryViewModel}", nameof(CategoryController), model.ToString());
        try
        {
            if (ModelState.IsValid)
            {
                int createdCategoryId = await categoryService.CreateCategory(model);

                List<CategoryPictureViewModel> categoryPictureViewModels = new List<CategoryPictureViewModel>();

                foreach (int picId in TransformTypes.SplitStringIntoListOfInt(model.uploadedImageIds))
                {
                    categoryPictureViewModels.Add(new CategoryPictureViewModel
                    {
                        CategoryId = createdCategoryId,
                        PictureId = picId
                    });
                    //model.CategoryPictures.ToList().Add(new CategoryPictureViewModel
                    //{
                    //    CategoryId = createdCategoryId,
                    //    PictureId = item
                    //});
                }

                int res = await categoryPictureService.CreateCategoryPictureAsync(categoryPictureViewModels);

                return RedirectToAction(nameof(Index));
            }

        }
        catch (ApplicationException ex)
        {
            logger.LogError("In {controller}, Creating category: {Message}, {Stacktrace}", nameof(CategoryController), ex.Message, ex.StackTrace);

            throw new ApplicationException($"Exception thrown controller when creating category: {ex.Message}");
        }
        catch (Exception ex)
        {
            logger.LogError("Unexpected error in {controller} when creating category: {Message}, {Stacktrace}", nameof(CategoryController), ex.Message, ex.StackTrace);
            
            throw new Exception($"Unexpected error in controller when creating category: {ex.Message}");
        }

        return StatusCode(StatusCodes.Status422UnprocessableEntity);
    }

【问题讨论】:

标签: c# asp.net asp.net-core exception try-catch


【解决方案1】:

您可以通过操作过滤器或使用自定义异常处理中间件来处理您的异常。 这取决于你的场景。但是有一个自定义的异常中间件或异常过滤器来处理你的异常是可以工作的,而且为了分离关注点更好。

使用中间件: Microsoft

异常过滤器: StackOverflow

【讨论】:

    猜你喜欢
    • 2016-08-22
    • 2021-04-30
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2019-09-18
    相关资源
    最近更新 更多