首页 > 解决方案 > .Net core 3.1 如何捕获所有错误并在辅助类中找到异常位置

问题描述

  1. 我正在使用app.UseExceptionHandler()中间件来捕获异常,但是出现了一些错误,例如 ex: new Uri(" empty str ")does not throw the error directly to the exception controller please find screen1 and 2? 发生错误时的屏幕 1

    按继续后异常会抛出异常控制器 按继续后的屏幕 2 为什么异常不直接转到异常控制器?

  2. 以及如何捕获发生在辅助类或任何不继承控制器类而不使用(尝试和捕获)的类中发生的异常,因为我需要一种动态方法来捕获所有项目文件中的任何异常?

标签: c#asp.net-coreexception

解决方案


您可以在基本控制器中添加带有函数回调的方法作为参数。

例如:基本控制器:

 public class BaseUIController
 {
  protected async Task<IActionResult> HandleExceptionCall(Func<Task<IActionResult>> call)
    {
        IActionResult result;
        try
        {
            //Your actual function call back pass here
            result = await call();
        }
        catch (Exception ex)
        {
           //Here, you can handle all the exception.
           result = View("Error");
        }
        return result;
    }
 }

例如:您的子控制器:

public class EmployeeController : BaseUIController
{        
    public async Task<IActionResult> GetEmployees()
    {
        return await HandleExceptionCall(async () =>
        {
           //Your api call here
           //Now, If any exception raised, you can handle in your base controller function.
        });
    }
}

推荐阅读