This article mainly introduces the relevant information of ASP.NET Core exceptions and Error handling in detail. It has certain reference value and interested friends can refer to it. In this chapter, we will discuss exception and error handling. When an error occurs in an ASP.NET Core application, you can handle it in a variety of different ways. Let's look at handling exceptions by adding a
middlewarethat will help us handle errors. To simulate an error, let's go to the application, run it, and see how the program behaves if we just
throw an exceptionYou will see that we failed to load this resource. There was an HTTP 500 error, Internal Server Error, and that page wasn't very helpful. It may be convenient to get some exception information.
Let's add another middleware 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); }); }
This middleware is a little different from others. Other middleware usually listens for incoming requests and makes some responses to the requests.
UseDeveloperExceptionPage does not care so much about what happens to the incoming request later in the pipeline.
It just calls the next middleware, and then waits to see if there will be an exception in the pipeline. If there is an exception, this middleware will give you an error page about the exception.
Now let’s run the application again. This will produce an output as shown in the screenshot below.
Now if an exception occurs in the program, you will see some exception information you want to see on the page. You'll also get a stack trace: Here you can see that an unhandled exception was thrown on line 37 of Startup.cs.
All this exception information will be very useful to developers. In fact, we may only want these exception messages to be displayed when the developer runs the application.
The above is the detailed content of ASP.NET Core Exception and Error Handling (8)_Practical Tips. For more information, please follow other related articles on the PHP Chinese website!