這篇文章給大家分享的是有關(guān)ASP.NET Core異常和錯(cuò)誤處理的案例的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過來看看吧。
在這一章,我們將討論異常和錯(cuò)誤處理。當(dāng) ASP.NET Core應(yīng)用程序中發(fā)生錯(cuò)誤時(shí),您可以以各種不同的方式來處理。讓我們來看看通過添加一個(gè)中間件來處理異常情況,這個(gè)中間件將幫助我們處理錯(cuò)誤。
要模擬出錯(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<Startup>(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)聽傳入的請求并對請求做一些響應(yīng)。
UseDeveloperExceptionPage不會(huì)如此在意傳入的請求在之后的管道會(huì)發(fā)生什么。
它只是調(diào)用下一個(gè)中間件,然后再等待,看看管道中是否會(huì)出現(xiàn)異常,如果有異常,這塊中間件會(huì)給你一個(gè)關(guān)于該異常的錯(cuò)誤頁面。
現(xiàn)在讓我們再次運(yùn)行應(yīng)用程序。將會(huì)產(chǎn)生一個(gè)如下面的屏幕截圖所示的輸出。
現(xiàn)在如果程序中出現(xiàn)異常,您將在頁面中看到一些想要看到的異常信息。你也會(huì)得到一個(gè)堆棧跟蹤:這里可以看到Startup.cs第37行有一個(gè)未處理的異常拋出。
所有這些異常信息對開發(fā)人員將非常有用。事實(shí)上,我們可能只希望當(dāng)開發(fā)人員運(yùn)行應(yīng)用程序時(shí)才顯示這些異常信息。
感謝各位的閱讀!關(guān)于ASP.NET Core異常和錯(cuò)誤處理的案例就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。