Exception handling in asp.net core?

I have a main asp.net application. Implementation of the configure method redirects the user to the Error page when an exception occurs (in an environment without development)

However, it only works if an exception occurs inside the controller. If an exception occurs outside the controller, for example, in my custom middleware, the user is not redirected to the error page.

How to redirect the user to the Error page if there is an exception in the middleware.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseApplicationInsightsExceptionTelemetry(); app.UseStaticFiles(); app.UseSession(); app.UseMyMiddleware(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } 

Update 1
I updated the code above with the following two lines missing from the original post.

  app.UseSession(); app.UseMyMiddleware(); 

I also found why app.UseExceptionHandler could not redirect to the error page.
When there is an exception in my intermediate code, app.UseExceptionHandler("\Home\Error") redirected to \Home\Error , as expected; but since this is a new request, my middleware ran again and threw an exception again.
So to solve the problem, I changed my middleware to only execute if context.Request.Path != "/Home/Error"

I am not sure if this is the right way to solve this problem, but its work.

 public class MyMiddleWare { private readonly RequestDelegate _next; private readonly IDomainService _domainService; public MyMiddleWare(RequestDelegate next, IDomainService domain) { _next = next; _domainService = domain; } public async Task Invoke(HttpContext context) { if (context.Request.Path != "/Home/Error") { if (context.User.Identity.IsAuthenticated && !context.Session.HasKey(SessionKeys.USERINFO)) { // this method may throw exception if domain service is down var userInfo = await _domainService.GetUserInformation(context.User.Name).ConfigureAwait(false); context.Session.SetUserInfo(userInfo); } } await _next(context); } } public static class MyMiddleWareExtensions { public static IApplicationBuilder UseMyMiddleWare(this IApplicationBuilder builder) { return builder.UseMiddleware<MyMiddleWare>(); } } 
+7
c # asp.net-core asp.net-core-mvc coreclr
source share
2 answers

You must write your own middleware to handle custom exception handling. And make sure you add it to the beginning (if possible) of the middleware stack, because exceptions that are executed in the middleware, โ€œearlyโ€ on the stack, will not be processed.

Example:

 public class CustomExceptionMiddleware { private readonly RequestDelegate _next; public CustomExceptionMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next.Invoke(context); } catch (Exception e) { // Handle exception } } } 
+5
source share

You can use UseExceptionHandler() to handle exceptions, put this code in your Startup.cs .

UseExceptionHandler can be used to handle exceptions worldwide. You can get all the details of the exception object, such as Stack Trace, Inner exception, and others. And then you can show them on the screen. Here

Here you can learn more about this diagnostic middleware and find how to use IExceptionFilter and create your own custom exception handler.

  app.UseExceptionHandler( options => { options.Run( async context => { context.Response.StatusCode = (int) HttpStatusCode.InternalServerError; context.Response.ContentType = "text/html"; var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null) { var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace}"; await context.Response.WriteAsync(err).ConfigureAwait(false); } }); } ); 

You should also remove the default setting, for example UseDeveloperExceptionPage() , if you use it, it always shows the default error page.

  if (env.IsDevelopment()) { //This line should be deleted app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } 
+5
source share

All Articles