Global Exception Handling in ASP.NET Core


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

.Net Core is free open-source platform that was developed by Microsoft along with .net core is a cross platform that supports all most operating systems like macOS, Windows and Linux.

.Net Core is a great platform embedded with a lot of characteristics which helps build cloud-based application, device applications. Just look at its characteristics that make it an efficient platform for the developers.

Table of Content

When strengthening an ASP.Net Core application, we can supportdifferent middleware components to personalize the manipulating of requests and responses, and even inspect, route, or reshaping the request and response messages that circulate through the pipeline.

What is exception handling?

Exception handling is handling known or unknown errors in code when such a situation arises and to gracefully recover for things.Like when running a question to a database over the LAN and you power off the machine running the database server, your code will raise an exception with a mistake code depend upon the database driver you are using.

If you would like to handle such a situation then you want to catch that exception code within the exception handler and print/log/email a message saying what happened and shut all open database, do any clean up like removing any half-written files and then exit the program with a proper exit code.

Exception handling is a cross-cutting apprehension in each and every application. Fortunately, we can take benefit of global exception handling in ASP.NET Core to assure that every exception is snatched, and to terminate the requirement to write additional boilerplate code each time we write a new controller or controller method.

Exception handling is nearly necessary once you affect external programs as you can't control their output or their state. So, during a way exception handling helps you recover without crashing your program and to urge important information to debug issues. We hope this helps.



Why we use exception?

Using cases in small programs like division is straightforward and efficient because you recognize all the possible inputs the user can make. However, in project, complicated programs with a vast number of combinations of inputs, implementing cases to solve/ to avert a particular case becomes tedious.

An exception is a mistake that occurred during program execution and disrupts the traditional flow of the program. To handle such errors by restricting them to harm the program to an excellent extent, exception handling is employed. These exception handlers tackle three type of errors: -

  1. Checked or compile-time exception
  2. Unchecked or Runtime exception
  3. Exception or logical errors

What is Exception Filter?

There is employed to handling expectation which occurs in action method this filter is often applied on the controller or action method. Exception filters are one of the main new features of C# exception filter allows you to specify a condition on a catch block:

There are many ways to implement exception handling globally

Example of Global Exception Handling Step by Step

Here,we willperform the simple Program for understanding the concept of Global Exception Handling.

For Testing Code in ASP.Net Core, firstly, we will create a new project. Creating a new ASP.Net Core application will open Visual Studio 2019 home screen select New Project Click on Ok.

global1

Fig: select project

First of all, the new project creation window pops up, then we have to select the ASP.NET Web Application C# Application. And select the MVC Checkbox and click on the next button. you will get the below display.

global2

Fig:Select Framework

After creating simple core project go to the Startup write below code in configuration method.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Threading.Tasks;
usingMicrosoft.AspNetCore.Builder;
usingMicrosoft.AspNetCore.Hosting;
usingMicrosoft.AspNetCore.HttpsPolicy;
usingMicrosoft.Extensions.Configuration;
usingMicrosoft.Extensions.DependencyInjection;
usingMicrosoft.Extensions.Hosting;

namespaceGlobalExceptionBlog
{
	publicclassStartup
    {
		publicStartup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

		publicIConfiguration Configuration { get; }


		publicvoidConfigureServices(IServiceCollection services)
        {
			services.AddControllersWithViews();
        }

		// This method gets called by the runtime.publicvoidConfigure(IApplicationBuilder app, IWebHostEnvironmentenv)
        {
			app.Run(context => { thrownew Exception("error"); });
			if (env.IsDevelopment() || env.IsStaging())
            {
				app.UseDeveloperExceptionPage();
            }
			else
            {
				app.UseExceptionHandler("/Home/Error");
            }

			app.UseHttpsRedirection();
			app.UseStaticFiles();

			app.UseRouting();

			app.UseAuthorization();

			app.UseEndpoints(endpoints =>
						{
			endpoints.MapControllerRoute(
					name: "default",
					pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

After that run the project you willget the belowdisplay. This exception is showing the code of error.

global3

Fig: Output Screen


Searching for Dedicated ASP.Net Core Web Developer ?

Your Search ends here.


Go to the home controller that was created by system and create error method written below.

using System;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Linq;
usingSystem.Threading.Tasks;
usingMicrosoft.AspNetCore.Mvc;
usingMicrosoft.Extensions.Logging;
usingGlobalExceptionBlog.Models;

namespaceGlobalExceptionBlog.Controllers
{
	publicclassHomeController : Controller
    {
		privatereadonlyILogger _logger;

		publicHomeController(ILogger logger)
			{
				_logger = logger;
			}

		publicIActionResultIndex()
			{
				returnView();
			}


		publicIActionResultPrivacy()
			{
				returnView();
			}

			[ResponseCache(Duration = 1, Location = ResponseCacheLocation.None, NoStore = true/false)]
		publicIActionResultError()
			{
				returnView(newErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
			}
    }
}

Create view of the error method right click on error method add new view and write below code,view is display error which one we want to display to the user.


@model ErrorViewModel
@{
    ViewData["Title"] = "Error";
}<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>	
        <strong>Request ID:</strong> <code>@Model.RequestId</code></p>
}
<h3>Development Mode</h3>

When you will run the project, you will get the belowscreen there is an exception user whenever project get this type of error,cursor will remove at this method.'

global4

Fig: Exception screen

After that click on continue button than you will see the below screen.

global5

Conclusion

This blog is helpful inunderstanding the concept of Global Exception Handling in Asp.Net Core as Exception Filter. This is used to display the error in simple words to the user on the websiteand display the error code to the user. Exception handling is a built Function in .Net Framework. Exception handling is managed by the run time error in .net core. Exception filters are useful for trapping exceptions that occur within MVC actions. We hope you learned well about this article on Global Exception Handling in Asp.Net Core as Exception Filter.

Global Exception Handling in ASP.NET Core

.Net Core is free open-source platform that was developed by Microsoft along with .net core is a cross platform that supports all most operating systems like macOS, Windows and Linux.

.Net Core is a great platform embedded with a lot of characteristics which helps build cloud-based application, device applications. Just look at its characteristics that make it an efficient platform for the developers.

Table of Content

When strengthening an ASP.Net Core application, we can supportdifferent middleware components to personalize the manipulating of requests and responses, and even inspect, route, or reshaping the request and response messages that circulate through the pipeline.

What is exception handling?

Exception handling is handling known or unknown errors in code when such a situation arises and to gracefully recover for things.Like when running a question to a database over the LAN and you power off the machine running the database server, your code will raise an exception with a mistake code depend upon the database driver you are using.

If you would like to handle such a situation then you want to catch that exception code within the exception handler and print/log/email a message saying what happened and shut all open database, do any clean up like removing any half-written files and then exit the program with a proper exit code.

Exception handling is a cross-cutting apprehension in each and every application. Fortunately, we can take benefit of global exception handling in ASP.NET Core to assure that every exception is snatched, and to terminate the requirement to write additional boilerplate code each time we write a new controller or controller method.

Exception handling is nearly necessary once you affect external programs as you can't control their output or their state. So, during a way exception handling helps you recover without crashing your program and to urge important information to debug issues. We hope this helps.



Why we use exception?

Using cases in small programs like division is straightforward and efficient because you recognize all the possible inputs the user can make. However, in project, complicated programs with a vast number of combinations of inputs, implementing cases to solve/ to avert a particular case becomes tedious.

An exception is a mistake that occurred during program execution and disrupts the traditional flow of the program. To handle such errors by restricting them to harm the program to an excellent extent, exception handling is employed. These exception handlers tackle three type of errors: -

  1. Checked or compile-time exception
  2. Unchecked or Runtime exception
  3. Exception or logical errors

What is Exception Filter?

There is employed to handling expectation which occurs in action method this filter is often applied on the controller or action method. Exception filters are one of the main new features of C# exception filter allows you to specify a condition on a catch block:

There are many ways to implement exception handling globally

Example of Global Exception Handling Step by Step

Here,we willperform the simple Program for understanding the concept of Global Exception Handling.

For Testing Code in ASP.Net Core, firstly, we will create a new project. Creating a new ASP.Net Core application will open Visual Studio 2019 home screen select New Project Click on Ok.

global1

Fig: select project

First of all, the new project creation window pops up, then we have to select the ASP.NET Web Application C# Application. And select the MVC Checkbox and click on the next button. you will get the below display.

global2

Fig:Select Framework

After creating simple core project go to the Startup write below code in configuration method.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Threading.Tasks;
usingMicrosoft.AspNetCore.Builder;
usingMicrosoft.AspNetCore.Hosting;
usingMicrosoft.AspNetCore.HttpsPolicy;
usingMicrosoft.Extensions.Configuration;
usingMicrosoft.Extensions.DependencyInjection;
usingMicrosoft.Extensions.Hosting;

namespaceGlobalExceptionBlog
{
	publicclassStartup
    {
		publicStartup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

		publicIConfiguration Configuration { get; }


		publicvoidConfigureServices(IServiceCollection services)
        {
			services.AddControllersWithViews();
        }

		// This method gets called by the runtime.publicvoidConfigure(IApplicationBuilder app, IWebHostEnvironmentenv)
        {
			app.Run(context => { thrownew Exception("error"); });
			if (env.IsDevelopment() || env.IsStaging())
            {
				app.UseDeveloperExceptionPage();
            }
			else
            {
				app.UseExceptionHandler("/Home/Error");
            }

			app.UseHttpsRedirection();
			app.UseStaticFiles();

			app.UseRouting();

			app.UseAuthorization();

			app.UseEndpoints(endpoints =>
						{
			endpoints.MapControllerRoute(
					name: "default",
					pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

After that run the project you willget the belowdisplay. This exception is showing the code of error.

global3

Fig: Output Screen


Searching for Dedicated ASP.Net Core Web Developer ?

Your Search ends here.


Go to the home controller that was created by system and create error method written below.

using System;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Linq;
usingSystem.Threading.Tasks;
usingMicrosoft.AspNetCore.Mvc;
usingMicrosoft.Extensions.Logging;
usingGlobalExceptionBlog.Models;

namespaceGlobalExceptionBlog.Controllers
{
	publicclassHomeController : Controller
    {
		privatereadonlyILogger _logger;

		publicHomeController(ILogger logger)
			{
				_logger = logger;
			}

		publicIActionResultIndex()
			{
				returnView();
			}


		publicIActionResultPrivacy()
			{
				returnView();
			}

			[ResponseCache(Duration = 1, Location = ResponseCacheLocation.None, NoStore = true/false)]
		publicIActionResultError()
			{
				returnView(newErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
			}
    }
}

Create view of the error method right click on error method add new view and write below code,view is display error which one we want to display to the user.


@model ErrorViewModel
@{
    ViewData[&quot;Title&quot;] = &quot;Error&quot;;
}<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>	
        <strong>Request ID:</strong> <code>@Model.RequestId</code></p>
}
<h3>Development Mode</h3>

When you will run the project, you will get the belowscreen there is an exception user whenever project get this type of error,cursor will remove at this method.'

global4

Fig: Exception screen

After that click on continue button than you will see the below screen.

global5

Conclusion

This blog is helpful inunderstanding the concept of Global Exception Handling in Asp.Net Core as Exception Filter. This is used to display the error in simple words to the user on the websiteand display the error code to the user. Exception handling is a built Function in .Net Framework. Exception handling is managed by the run time error in .net core. Exception filters are useful for trapping exceptions that occur within MVC actions. We hope you learned well about this article on Global Exception Handling in Asp.Net Core as Exception Filter.

  • Pin It
TOP