How to handle errors in asp.net core globally or Centralize

Centralize way to handle errors in asp.net core by sagar jaybhay

In Case You do not handle the error at a respective method-level then our global exception handler comes in picture and display appropriate message.

Below are the steps to add a global filter in your asp.net core application to handle errors in asp.net core globally or Centralize way

Step 1:

Add below the line of code in your configure method in startup class.

app.UseExceptionHandler("/Error");

Now your code likes below.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions {SourceCodeLineCount = 10};
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }
            else
            {
                app.UseExceptionHandler("/Error");

                //app.UseStatusCodePagesWithReExecute("/Error/{0}");
                //  app.UseStatusCodePagesWithRedirects("/Error/{0}");

            }

            app.UseStaticFiles();
            app.UseHsts();
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
                //routes.MapRoute(name: "default", template: "sagar/{controller=Home}/{action=Index}/{id?}");
            });
            
        }
Global Exception Handling In Asp.net core part 1

In process of Centralize way to handle errors, we pass Error which is our route and for that we created one controller whose name is errorcontroller and in that we add error method.

public class ErrorController : Controller
    {
        
        [AllowAnonymous]
        [Route("Error")]
        public IActionResult Error()
        {
            var exceptionfeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
            ViewBag.ExceptionPath = exceptionfeature.Path;
            ViewBag.ExceptionMessage = exceptionfeature.Error.Message;
            ViewBag.StackTrace = exceptionfeature.Error.StackTrace;

            return View();

        }

    }

In this method we use HttpContext object from that we get exception features and we extract details from that object. Now we store these details in ViewBag as you can see above method.

Step 2:

Add the respective view for displaying an error and all the details which you need to display. Real life we don’t show all details of exception to end-user rather than we write that all exception in text file or database but for demo we display that error. Below is our view code for error.

@{
    ViewData["Title"] = "Error";
}

<h1>I m Global Exception Handle Page</h1>



<div class="card">

    <div class="card-header">
        Error Path: @ViewBag.ExceptionPath;
    </div>

    <div class="card-body">
        Exception Message: @ViewBag.ExceptionMessage;
    </div>
    
    <div class="card-footer">
        Stack Trace:@ViewBag.StackTrace
    </div>
</div>
Global Exception Handling In Asp.net core part -view

Output

You can see the output of the above global exception handler.

Global Exception Handling In Asp.net core part -OutPut

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts