這篇文章將為大家詳細(xì)講解有關(guān)ASP.NET Core中異常和錯(cuò)誤處理怎么辦,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
要模擬出錯(cuò),讓我們轉(zhuǎn)到應(yīng)用程序,運(yùn)行,如果我們只是拋出異常的話,看看程序是如何運(yùn)轉(zhuǎn)轉(zhuǎn)的。
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(args); } }
它只會(huì)拋出一個(gè)非常通用的異常信息。保存Startup.cs頁面并運(yùn)行您的應(yīng)用程序。
您將看到我們未能加載此資源。出現(xiàn)了一個(gè) HTTP 500 錯(cuò)誤,內(nèi)部服務(wù)器錯(cuò)誤,那個(gè)頁面不是很有幫助。它可能很方便得到一些異常信息。
讓我們添加另一個(gè)中間件 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); }); }
這個(gè)中間件與其他的有點(diǎn)不同,其他中間件通常監(jiān)聽傳入的請(qǐng)求并對(duì)請(qǐng)求做一些響應(yīng)。
UseDeveloperExceptionPage不會(huì)如此在意傳入的請(qǐng)求在之后的管道會(huì)發(fā)生什么。
它只是調(diào)用下一個(gè)中間件,然后再等待,看看管道中是否會(huì)出現(xiàn)異常,如果有異常,這塊中間件會(huì)給你一個(gè)關(guān)于該異常的錯(cuò)誤頁面。
現(xiàn)在讓我們?cè)俅芜\(yùn)行應(yīng)用程序。將會(huì)產(chǎn)生一個(gè)如下面的屏幕截圖所示的輸出。
現(xiàn)在如果程序中出現(xiàn)異常,您將在頁面中看到一些想要看到的異常信息。你也會(huì)得到一個(gè)堆棧跟蹤:這里可以看到Startup.cs第37行有一個(gè)未處理的異常拋出。
所有這些異常信息對(duì)開發(fā)人員將非常有用。事實(shí)上,我們可能只希望當(dāng)開發(fā)人員運(yùn)行應(yīng)用程序時(shí)才顯示這些異常信息。
關(guān)于“ASP.NET Core中異常和錯(cuò)誤處理怎么辦”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。