ASP.NET Core - 異常



在本章中,我們將討論異常和錯誤處理。當您的 ASP.NET Core 應用程式中發生錯誤時,您可以透過多種方式處理它們。讓我們看看診斷包中提供的另一部分中介軟體。這部分中介軟體將幫助我們處理錯誤。

為了模擬錯誤,讓我們轉到app.Run,看看如果每次我們點選這部分中介軟體時都丟擲一個異常,應用程式的行為如何。

using Microsoft.AspNet.Builder; 
using Microsoft.AspNet.Hosting; 
using Microsoft.AspNet.Http; 

using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Configuration;  

namespace FirstAppDemo { 
   public class Startup { 
      public Startup() { 
         var builder = new ConfigurationBuilder() 
            .AddJsonFile("AppSettings.json"); 
         Configuration = builder.Build(); 
      }  
      public IConfiguration Configuration { get; set; }  
        
      // This method gets called by the runtime. 
      // Use this method to add services to the container. 
      // For more information on how to configure your application, 
      // visit http://go.microsoft.com/fwlink/?LinkID=398940 
      public void ConfigureServices(IServiceCollection services) { 
      }  
      
      // This method gets called by the runtime. 
      // Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app) { 
         app.UseIISPlatformHandler();  
         app.UseRuntimeInfoPage();  
         
         app.Run(async (context) => { 
            throw new System.Exception("Throw Exception"); 
            var msg = Configuration["message"]; 
            await context.Response.WriteAsync(msg); 
         });  
      }  
        
      // Entry point for the application. 
      public static void Main(string[] args) => WebApplication.Run<Startup>(args); 
   }   
} 

它只會丟擲一個帶有非常通用訊息的異常。儲存Startup.cs頁面並執行您的應用程式。

Generic Message

您將看到我們未能載入此資源。出現了一個 HTTP 500 錯誤,一個內部伺服器錯誤,這並沒有什麼幫助。獲取一些異常資訊可能會更好。

讓我們新增另一部分中介軟體,即UseDeveloperExceptionPage

// This method gets called by the runtime.  
// Use this method to configure the HTTP request pipeline. 
public void Configure(IApplicationBuilder app) { 
   app.UseIISPlatformHandler();  
   app.UseDeveloperExceptionPage(); 
   app.UseRuntimeInfoPage();  
   
   app.Run(async (context) => { 
      throw new System.Exception("Throw Exception"); 
      var msg = Configuration["message"]; 
      await context.Response.WriteAsync(msg); 
   });  
}
  • 這部分中介軟體與其他中介軟體略有不同,其他中介軟體通常檢視傳入的請求並對該請求做出一些決定。

  • UseDeveloperExceptionPage 不太關心傳入的請求,而更關心管道中稍後發生的事情。

  • 它將呼叫下一個中介軟體,但隨後它將等待檢視管道中稍後是否有任何內容生成異常,如果存在異常,這部分中介軟體將為您提供一個錯誤頁面,其中包含有關該異常的其他資訊。

現在讓我們再次執行應用程式。它將生成如下面的螢幕截圖所示的輸出。

Internal Server Error

現在您將看到一些您期望在開發中出現錯誤時看到的資訊。您還將獲得一個堆疊跟蹤,並且可以看到在 Startup.cs 的第 37 行丟擲了一個未處理的異常。

您還可以檢視原始異常詳細資訊,所有這些資訊對於開發人員都非常有用。事實上,我們可能只希望在開發人員執行應用程式時顯示此資訊。

廣告

© . All rights reserved.