c# - .Net core 3.1 如何捕获所有错误并在辅助类中找到异常位置
问题描述
我正在使用
app.UseExceptionHandler()
中间件来捕获异常,但是出现了一些错误,例如 ex:new Uri(" empty str ")
does not throw the error directly to the exception controller please find screen1 and 2?
按继续后异常会抛出异常控制器 为什么异常不直接转到异常控制器?以及如何捕获发生在辅助类或任何不继承控制器类而不使用(尝试和捕获)的类中发生的异常,因为我需要一种动态方法来捕获所有项目文件中的任何异常?
解决方案
您可以在基本控制器中添加带有函数回调的方法作为参数。
例如:基本控制器:
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.
});
}
}
推荐阅读
- xamarin - Xamarin 条目在删除最后一个字符时不会引发绑定项目属性的设置器
- docker - 在 macbook 上使用 docker 安装 sql server 时出错
- android - Android 用 Livedata 和 ViewModel 替换 Greenrobot 事件机制
- python - 如何在火花中合并数据框中的列表
- data-structures - 通过删除给定元素并将剩余位置填充 1 来重新排列数组
- javascript - 仅在月份选择器中获取当前月份,其他月份必须禁用
- numpy - RuntimeWarning:使用 ODEINT 和 solve_bvp 求解 Poisson-Boltzmann 方程时在 sinh 中遇到溢出
- reactjs - 反应组件无法找到我的 CSS 类
- json - 将 Typescript 与 JSON 结合使用的模式是什么?
- javascript - 在 HTML 中按 Javascript 搜索过滤器