问题描述
我有一个asp.net core 3.1应用程序,我创建了异常处理中间件来处理所有全局错误。我的中间件代码是
public static class ExceptionHandler
{
public static void ConfigureExceptionHandler(this IApplicationBuilder app)
{
app.UseExceptionHandler(appError =>
{
appError.Run(async context =>
{
var logger = (ILogger)context.RequestServices.GetService(typeof(ILogger<Startup>));
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contextFeature != null)
{
logger.LogError(contextFeature.Error,"Error in Service");
context.Response.StatusCode = (int)GetErrorCode(contextFeature.Error);
await context.Response.WriteAsync(JsonConvert.SerializeObject(contextFeature.Error.Message));
}
});
});
}
private static HttpStatusCode GetErrorCode(Exception ex)
{
switch (ex)
{
case ValidationException _:
return HttpStatusCode.BadRequest;
case NotImplementedException _:
return HttpStatusCode.NotImplemented;
default:
return HttpStatusCode.InternalServerError;
}
}
}
并且我在启动文件中使用它
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.ConfigureExceptionHandler();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseOpenApi();
app.UseSwaggerUi3();
}
问题是异常在中间件中被捕获并且消息已正确记录,但是随后我看到在日志中重复出现相同消息,上下文为“ Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware”,EventId为“ UnhandledException”,这向我表明该异常不会被视为已处理,而且还会使我的应用一次次崩溃。
有人可以让我知道我在想什么吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)