Global exception handling in asp.net core

Global exception handling is a way to handle unhandled exceptions in asp.net core.

Add a middleware UseExceptionHandler to the pipeline that will catch exceptions, log them, reset the request path and re-execute the request. The request will not be re-executed if the response has already started.

Add UseExceptionHandler code in Startup.Configure method as stated below. This will redirect to Error action.

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

Now exception can be captured using IExceptionHandlerFeature in the Error Action.

 Public IActionResult Error()
 {    
     var errorFeature = HttContext.Features.Get<IExceptionHandlerFeature>();
     var error = errorFeature.Error;
     var errorMessage= error.Message;
     var errorStackTrace = error.StackTrace;
     return View();
 }

Leave a Reply

Your email address will not be published. Required fields are marked *