ASP.NET 核心中的全域性異常處理

UseExceptionHandler 可用於全域性處理異常。你可以獲取異常物件的所有詳細資訊,如 Stack Trace,Inner 異常等。然後你可以在螢幕上顯示它們。你可以輕鬆地實現這樣的。

app.UseExceptionHandler(
 options => {
    options.Run(
    async context =>
    {
      context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
      context.Response.ContentType = "text/html";
      var ex = context.Features.Get<IExceptionHandlerFeature>();
      if (ex != null)
      {
        var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace }";
        await context.Response.WriteAsync(err).ConfigureAwait(false);
      }
    });
 }
);

你需要將它放在 startup.cs 檔案的 configure() 中。