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 页面并运行您的应用程序。

通用消息

您会看到我们加载此资源失败。 有一个 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 不太关心传入的请求,因为它会处理稍后在管道中发生的事情。

  • 它只会调用下一个中间件,但随后它会等待,看看管道后面是否有任何东西产生异常,如果有异常,这个中间件会给你一个错误页面,其中包含有关该异常的一些附加信息。

现在让我们再次运行该应用程序。 它将产生如下屏幕截图所示的输出。

内部服务器错误

现在您将看到一些在开发过程中出现错误时您会期望得到的信息。 您还将获得一个堆栈跟踪,您可以看到在 Startup.cs 的第 37 行抛出了一个未处理的异常。

您还可以查看原始异常详细信息,所有这些信息对开发人员都非常有用。 事实上,我们可能只想在开发人员运行应用程序时显示此信息。



关于我们 | 隐私条款 | 学习路线
返回顶部