ASP.NET Core

Exception Handling in Asp.NET Core 3.1

Exception Handling in Asp.NET Core 3.1

Exception Handling in Asp.NET Core 3.1

Exception handling is one of the most important features of any application. Fortunately, ASP.NET Core includes a middleware that makes exception handling easy.
By default, ASP.NET Core returns a simple status code for any exception that occurs in an application

public class Startup {
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {            
        app.Run(context => { throw new Exception("error"); });
    }
}




Handle Exceptions
Install Microsoft.AspNetCore.Diagnostics Package
To handle exceptions and display user friendly messages, we need to install Microsoft.AspNetCore.Diagnostics NuGet package and add middleware in the Configure() method. If you are using Visual Studio templates to create ASP.NET Core application then this package might be already installed.
The Microsoft.AspNetCore.Diagnostics package includes following extension methods to handle exceptions in different scenario:
1. UseDeveloperExceptionPage
    The UseDeveloperExceptionPage extension method adds middleware into the request pipeline which displays developer friendly exception detail page. This helps developers in tracing errors that occur during development phase.
    This middleware displays sensitive information, it is advisable to add it only in development environment.

public class Startup {
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment() || env.IsStaging()) {
            app.UseDeveloperExceptionPage();
        }
        app.Run(context => { throw new Exception("error"); });
    }
}


The developer exception page includes 5 tabs
Stack: The Stack tab gives the information of stack trace, which indicates where exactly the exception occurred, the file name, and the line number that caused the exception.
Query: The Query tab gives information about the query strings.
Cookies: The Cookies tab displays the information about the cookies set by the request.
Header: The Header tab gives information about the headers which is sent by the client when he makes the request.
Routing: The Routing tab gives information about the Route Pattern and Route HTTP Verb type of the method, etc.



2. UseExceptionHandler
In MVC Core application, we might want some other controller to handle all exceptions and display custom user friendly error messages. The UseExceptionHandler extension method allows us to configure custom error handling route. This is useful when an application runs under production environment.

public void Configure(IApplicationBuilder app, IHostingEnvironment env){

    if (env.IsDevelopment() || env.IsStaging())    {
        app.UseDeveloperExceptionPage();
    }
    else  {
        app.UseExceptionHandler("/Home/Error");
    }
}

// the UseExceptionHandler("/Home/Error") sets the error handler path.
// If an error occurred in the MVC application then it will redirect the request to /home/error




DeveloperExceptionPage Middleware Options (3.1)
If you are working with any older versions of .NET Core Application, in order to display a page that shows detailed information about the unhandled exception, you need to configure the Developer Exception Page Middleware in the Request Processing Pipeline. To do so, you need to modify the Configure() Method of the Startup class as shown below to add the Developer Exception Page middleware, which will handle the unhandled exception that occurred in your application.
UseDeveloperExceptionPage => To customize UseDeveloperExceptionPage middleware, we need to use the DeveloperExceptionPageOptions object.
UseDefaultFiles => To customize UseDefaultFiles middleware, use the DefaultFilesOptions object
UseStaticFiles => To customize UseStaticFiles middleware, use the StaticFileOptions object
UseFileServer => To customize UseFileServer middleware, use the FileServerOptions object
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        var app = builder.Build();
        //If the Environment is Development, Please Show the Unhandled Exception Details
        if (app.Environment.IsDevelopment())
        {
            //Create an Instance of DeveloperExceptionPageOptions to Customize
            //UseDeveloperExceptionPage Middleware Component
            DeveloperExceptionPageOptions developerExceptionPageOptions = new DeveloperExceptionPageOptions
            {
                SourceCodeLineCount = 5
            };
            //Passing DeveloperExceptionPageOptions Instance to UseDeveloperExceptionPage Middleware Component
            app.UseDeveloperExceptionPage(developerExceptionPageOptions);
        }
        app.MapGet("/", async context =>
        {
            int Number1 = 10, Number2 = 0;
            int Result = Number1 / Number2; //This statement will throw Runtime Exception
            await context.Response.WriteAsync($"Result : {Result}");
        });
        //This will Start the Application
        app.Run();
    }
}













Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram