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.
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.
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.
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: -
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.
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.
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.
Fig: Output Screen
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"; }
Request ID: @Model.RequestId
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.'
Fig: Exception screen
After that click on continue button than you will see the below screen.
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.
July 29, 2021
July 22, 2021
July 20, 2021
July 16, 2021
Well do everything we can to make our next best project!
Check out our most recent blogs
July 29, 2021
What is Angular? Angular is a frontend development framework used for building single-page client applications using HTML and Typescript. It is written in Typescript. What...
July 22, 2021
What is a Compiler? A compiler is nothing but a part of code that converts one programming language to another. If we talk about some simple programming languages like C, C++,...
July 20, 2021
Introduction Angular is a remarkable framework that may be used to create mobile and desktop web apps with spectacular UIs. It's made with JavaScript. we can utilize HTML, CSS,...
Well do everything we can to make our next best project!