Monday, February 18, 2019

Adding UseDeveloperExceptionPage Middleware

Exception Handling is an integral part of any application, if exceptions are not handles we will see the system exception page like status code 500, this will not provide much information to the developers to investigate on the exception. In the previous .Net Framework MVC by default the stack trace and line information will be displayed in the browser, but in .Net core it shows a generic error message.

In Asp.Net core we need to add a UseDeveloperExceptionPage middleware, to display stack trace and additional information about the exception. To see how this middleware works let us explicitly throw an exception in the Configure() method as follows to see the result.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.Run(async (context) =>
            {
                throw new System.Exception("Some Exception");
                await context.Response.WriteAsync("Hello World!");
            });
        }

When we run the application with this exception, we will see the following output in the browser. Notice that it does not provide much information about the exception and stack trace. 


Now let us add the UseDeveloperExceptionPage middleware as follows and run the application.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();

            app.Run(async (context) =>
            {
                throw new System.Exception("Some Exception");
                await context.Response.WriteAsync("Hello World!");
            });
        }

This time we see more details about the exception including the stack trace, and source code line information. The output will be as follows.




Search Flipkart Products:
Flipkart.com

No comments: