我正在使用Aspnet core 3.0,并且已经为异常处理配置了ElmahCore。但是,他们建议从文档中使用
捕获异常public IActionResult Test()
{
HttpContext.RiseError(new InvalidOperationException("Test"));
...
}
我如何配置Elmahcore以自动捕获并记录所有异常?还是我每次想捕获和记录异常时都必须写HttpContext.RiseError
吗?
就像我必须在每个try catch
中放置ActionResult
个块并在我所有的catch块中调用HttpContext.RiseError()
吗?
是否可以使用ElmahCore全局配置捕获和记录异常的方法?
基于@ Fei-han的建议和此global error handling link,我能够在生产环境中全局记录异常。在Startup.cs文件中,当我的应用程序在生产模式下运行时,请确保已配置ExceptionHandler
,例如
Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseElmah();
//Other configurations
}
这可确保每当发生未捕获的异常时,它将调用本地控制器的错误操作方法
家庭控制器
using Microsoft.AspNetCore.Diagnostics;
public IActionResult Error()
{
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionFeature != null)
{
// Get the exception that occurred
Exception exceptionThatOccurred = exceptionFeature.Error;
//log exception using ElmahCore
HttpContext.RiseError(exceptionThatOccurred);
}
//Return custom error page (I have modified the default html of
//Shared>Error.cshtml view and showed my custom error page)
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
现在我的所有异常都已记录,并且我还显示了一个自定义错误页面以响应异常。