我有这两个 Controller Action
#1将抛出除以零的异常
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
var x = 0;
var y = 5 / x;
return View();
}
#2异常(exception)之后,我希望在生产模式下调用此操作。
public IActionResult Error()
{
var model = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier };
return View(model);
}
我有两个问题
我不想在每个 Action 或重复 Action 过滤器属性中使用try catch语法,因为我想像在核心版本之前的
global.asax
中那样实现一般的异常处理程序。我的startup.cs非常简单。
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseStatusCodePages();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
任何想法 ?
最佳答案
我们可以使用下面的代码行
var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
var error = feature?.Error;
_logger.LogError("Oops!", error);
return View("~/Views/Shared/Error.cshtml", error);
您能否引用以下链接以获取更多详细信息
Click
关于error-handling - Controller 中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51131470/