gpt4 book ai didi

c# - 如何配置多个异常处理程序

转载 作者:行者123 更新时间:2023-11-30 12:19:56 29 4
gpt4 key购买 nike

我正在尝试将我的中间件管道配置为使用 2 个不同的异常处理程序来处理相同的异常。例如,我正在尝试让我的自定义处理程序和内置 DeveloperExceptionPageMiddleware 如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.ConfigureCustomExceptionHandler();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.ConfigureCustomExceptionHandler();
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}

我的目标是让自定义处理程序执行自己的操作(日志记录、遥测等),然后将 (next()) 传递给显示页面的其他内置处理程序。我的自定义处理程序如下所示:

public static class ExceptionMiddlewareExtensions
{
public static void ConfigureCustomExceptionHandler(this IApplicationBuilder app)
{
app.UseExceptionHandler(appError =>
{
appError.Use(async (context, next) =>
{
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contextFeature != null)
{
//log error / do custom stuff

await next();
}
});
});
}
}

我无法让 CustomExceptionHandler 将处理传递给下一个中间件。我得到以下页面:

404错误:

enter image description here

我尝试切换顺序,但随后开发人员异常页面接管并且未调用自定义异常处理程序。

我正在尝试做的事情是否可行?

更新:

The solution was to take Simonare's original suggestion and re-throw the exception in the Invoke method. I also had to remove any type of response-meddling by replacing the following in HandleExceptionAsync method:

context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);

with:

return Task.CompletedTask;

最佳答案

您可以考虑在Home/Error 下添加日志记录,而不是调用两个不同的异常处理中间件

[AllowAnonymous]
public IActionResult Error()
{
//log your error here
return View(new ErrorViewModel
{ RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

或者,您可以使用自定义异常处理中间件

public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;

public ErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context, IHostingEnvironment env)
{
try
{
await _next(context);
}
catch (Exception ex)
{
if (!context.Response.HasStarted)
await HandleExceptionAsync(context, ex, env);
throw;
}
}

private Task HandleExceptionAsync(HttpContext context, Exception exception, IHostingEnvironment env)
{
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
var message = exception.Message;

switch (exception)
{
case NotImplementedException _:
code = HttpStatusCode.NotImplemented;
break;
//other custom exception types can be used here
case CustomApplicationException cae: //example
code = HttpStatusCode.BadRequest;
break;
}

Log.Write(code == HttpStatusCode.InternalServerError ? LogEventLevel.Error : LogEventLevel.Warning, exception, "Exception Occured. HttpStatusCode={0}", code);


context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return Task.Completed;
}
}

并简单地在 IApplicationBuilder 方法中注册它

  public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<ErrorHandlingMiddleware>();
}

关于c# - 如何配置多个异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54361976/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com