ASP.NET Core异常和错误处理(8)
网络编程 2021-07-04 22:41www.168986.cn编程入门
这篇文章主要为大家详细介绍了ASP.NET Core异常和错误处理的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
在这一章,我们将讨论异常和错误处理。当 ASP.NET Core应用程序中发生错误时,您可以以各种不同的方式来处理。让我们来看看通过添加一个中间件来处理异常情况,这个中间件将帮助我们处理错误。
要模拟出错,让我们转到应用程序,运行,如果我们只是抛出异常的话,看看程序是如何运转转的。
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./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不会如此在意传入的请求在之后的管道会发生什么。
它只是调用下一个中间件,然后再等待,看看管道中是否会出现异常,如果有异常,这块中间件会给你一个关于该异常的错误页面。
现在让我们再次运行应用程序。将会产生一个如狼蚁网站SEO优化的屏幕截图所示的输出。
现在如果程序中出现异常,您将在页面中看到一些想要看到的异常信息。你也会得到一个堆栈跟踪:这里可以看到Startup.cs第37行有一个未处理的异常抛出。
所有这些异常信息对开发人员将非常有用。事实上,我们可能只希望当开发人员运行应用程序时才显示这些异常信息。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程