Learn c# exception handling

Facebook
Twitter
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

In .NET Core, you can create exceptional filters apart from the conventional try-catch exception handling. It is one of the most significant features in an application that can save it from getting failed in terms of expectations. ASP.NET Core includes a middleware that provides an easy way to handle exceptions in an application. This article covers the certain approaches to handle errors in ASP.NET Core applications.

What is Exception Handling?

In computer programming, exceptional handling is a mechanism to handle the occurrence of all the runtime exceptions in an application. An exception is an unanticipated or undesirable event that can occur in a program that can disrupts the normal workflow or stops the application. Each exception is a part of Throwable class. It ensures that the flow of a program continues to run, and it does not break whenever there is an exception occur in a program and it helps to handle the exceptions gracefully.

Why an Exception Occur?

There are many reasons when your application can have an unexpected output and it generates an exception in it. You take an example of such scenarios, like accessing a file which does not exist on the disk, divide by zero, incorrect input data type, bad or no network connection, I/O file used by another resource and an application is trying to access it, and many more.

You can save your application from getting to be closed abruptly by trying to cover all the statements in try-catch block followed by a final block, so if there is any suspicious statement anywhere in the block, the catch block will handle the exception.

Install Microsoft.AspNetCore.Diagnostics Package

In ASP.NET Core, whenever there is an exception occurs, it displays a simple status code HTTP ERROR 500 in an application. To display the user friendly exceptions or the detail of the exceptions, you need to install Microsoft.AspNetCore.Diagnostics package through NuGet package manager or console. After installing the package, you need to add a middleware in the Configure() method. If you are using ASP.NET Core application template from Visual Studio, then it will already have this package.

It has two extension methods to capture the exceptions and handles them separately:

  1. UseDeveloperExceptionPage
  2. UseExceptionHandler

What is Developer Exception Page?

ASP.NET Developer page allows developers to see the exceptions in development environment as it runs early in the pipeline to catch unhandled exceptions. All the exceptions must be hidden from the end users in a Production environment, and it is advisable not to put sensitive information in the development environment. It can have the following information:

  • Stack Trace

The Stack Trace tab displays information of stack trace that will show where the exception has occurred along with the line number and file name.

  • Query Strings

The Query Strings tab displays information about the query strings.

  • Cookies

The Cookies tab displays information about the cookies set by the request

  • Headers

The Header tab displays the information about the headers which are sent by the client with the request.

  • Route

The Route tab displays information about the route pattern.

public class Startup
{
    public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment )
    {
        if (hostingEnvironment.IsDevelopment() || hostingEnvironment.IsStaging() )
        {
            applicationBuilder.UseDeveloperExceptionPage();
        }

        applicationBuilder.Run( context => { throw new Exception("An error has occurred. Please check and try again. ") ; });
    }
}

Customize the UseDeveloperExceptionPage Middleware in ASP.NET Core

ASP.NET Core allows you to customize your UseDeveloperExceptionPage by following any of the given method:

  • UseDeveloperExceptionPage

It allows you to customize this middleware by using the DeveloperExceptionPageOptions object.

  • UseDefaultFiles

It allows you to customize this middleware by using the DefaultFilesOptions object.

  • UseStaticFiles

It allows you to customize this middleware by using the StaticFileOptions object.

  • UseFileServer

It allows you to customize this middleware by using the FileServerOptions object.

What is UseExceptionHandler?

In ASP.NET Core, you can use UseExceptionHandler middleware to handle exceptions in an application. You can take a custom model class that can hold the information in a model. It allows you to handle the exception in a custom manner and can display user friendly errors on the screen.

using System.Text.Json;
namespace ErrorHandleGLobal.Models
{
    public class ErrorModel
    {
        public int StatusCode { get; set; }
        public string Message { get; set; }
        public override string ToString()
        {
            return JsonSerializer.Serialize(this) ;
        }
    }
}

After creating a model class, you are required to create another static class that will handle the exception and write the log and work as an extension.

using LoggerService;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using System.Net;
using ErrorHandleGlobal.Models;

namespace ErrorHandleGlobal.Extensions
{
    public static class ExceptionMiddlewareExtensions
    {
        public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerManager _LogManager)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "application/json";

                    var contextFeature = context.Features.Get();
                    if( contextFeature != null)
                    { 
                        _LogManager.WriteLogError("Something went wrong : {contextFeature.Error} " );

                        await context.Response.WriteAsync(new ErrorDetails ()
                        {
                            StatusCode = context.Response.StatusCode,
                            Message = "There is an Internal Server Error. Please try again" }.ToString());
                    }
                }) ;
            });
        }
    }
}

Access Exception

IExceptionHandlerPathFeature is used to access exceptions in an error handler.


        var exceptionHandler = HttpContext.Features.Get() ;

        if (exceptionHandler?.Error is FileNotFoundException)
        {
            ExceptionMessage = " The requested file is not found. Please try again.";
        }

        if ( exceptionHandler?.Path == "/")
        {
            ExceptionMessage ?? = string.Empty;
            ExceptionMessage += " Page : Index " ;
        }

Error Status Code Pages

ASP.NET Core does not provide a default page for HTTP error status code. It is essential to enable the default text-only header status code for an application in Program class.

var app = builder.Build();

if (! app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/ Error ");
    app.UseHosts();
}

app.UseStatusCodePages();

Customizing Error Messages

ASP.NET Core allows you to customize your messages as per the requirement in your application.


public async Task InvokeAsync(HttpContext httpContext)
{
    try
    {
        await _next(httpContext);
    }
    // Custom Exception Handling and Message
    catch (AccessViolationException avExcep)
    {
        _logManager.WriteLogError(" A new violation exception has been thrown: { avExcep }") ;
        await HandleExceptionAsync(httpContext, avExcep);
    }
    catch (Exception excep)
    {
        _ logManager.WriteLogError("Attention!, something went wrong : { excep }");
        await HandleExceptionAsync (httpContext, excep);
    }
}
Facebook
Twitter
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.