【问题标题】:Centralized Exception Handling not working集中式异常处理不起作用
【发布时间】:2019-03-28 23:37:11
【问题描述】:

我正在我的 ASPNetCore 应用程序中测试集中式异常处理,并想看看是否抛出了意外异常,它将由 app.UseExceptionHandler() 中间件正确处理并记录到特定的日志记录目标。我断开了 SQL 数据库的连接,期望在抛出 System.Data.SqlClient.SqlException 的 DbContext 类构造函数中看到 Database.EnsureCreated() 方法。问题是它确实抛出了这样的异常,但它出现在本地,而不是由集中式错误处理程序处理。最终结果是客户端永远不会收到解释状态码 500 所发生情况的响应消息。

这似乎很奇怪,因为处理程序可以正常工作,但我在控制器中抛出了一个异常。

这是我的集中式异常处理程序配置:

app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    var errorFeature = context.Features.Get<IExceptionHandlerFeature>();

                    if (errorFeature != null)
                    {
                        var exception = errorFeature.Error;              

                        logger.LogError(exception.ToString());

                        await context.Response.WriteAsync("An unexpected error occurred! Try again later");

                    }

                });
            });     

谁能告诉我提示我可能做错了什么?有没有人遇到过类似的问题?

【问题讨论】:

  • 您是否尝试在没有附加调试器的情况下运行您的程序?根据您的配置,Visual Studio 会在第一次机会异常时中断
  • @Andre Kraemer 谢谢。按Ctrl+F5就可以了,但是我还是不明白为什么。
  • 可能和order of middleware有关。

标签: asp.net-core


【解决方案1】:

您的代码对我来说看起来不错。您正在经历的是第一次机会例外。这意味着抛出了一个可能最终得到处理的异常。在运行时,您的 ExceptionHandler 应该完美地处理您的异常。

但是,在调试时,Visual Studio 会因该异常而中断。可以在异常设置 (Debug &gt; Windows &gt; Exception Settings) 中配置 Visual Studio 的行为。有关更多信息,请参阅Microsoft Docs

所以你基本上要做的就是告诉 Visual Studio 继续调试 SqlException

【讨论】:

    【解决方案2】:

    您可以使用自己的中间件作为第一人称处理异常

    public class ExceptionFilter: IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            String message = String.Empty;
    
            Type exceptionType = context.Exception.GetType();
            if (exceptionType == typeof(NotImplementedException))
            {
                message = "A server error occurred.";
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                context.Result = new RedirectResult("/Home/Index");
            }
            else if (exceptionType == typeof(AppException))
            {
                message = context.Exception.ToString();
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Result = new RedirectResult("/Home/Index");
            }
            //HttpResponse response = context.HttpContext.Response;
            //response.StatusCode = (int)status;
            //context.Result = new RedirectResult("/Home/Index");
        }
    }
    

    在你的Startup.cs

    app.UseMiddleware(typeof(ExceptionFilter));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-06
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2014-10-19
      • 2016-03-18
      • 2019-05-20
      相关资源
      最近更新 更多