Blog

Filter posts by Category Or Tag of the Blog section!

Using Middleware to handle exceptions in asp.net core

Thursday, 08 November 2018

There are a few ways to handle exceptions in asp.net core 2.1. using Middleware is so straightforward, and it handles the application exceptions as well as exceptions from filters and you can have full control over. Look at the following class:

 

 public class MiddlewareExceptionHandler

    {

        private readonly RequestDelegate _requestDelegate;

 

        public MiddlewareExceptionHandler(RequestDelegate requestDelegate)

        {

            _requestDelegate = requestDelegate;

        }

 

        public async Task Invoke(HttpContext context)

        {

            try

            {

                await _requestDelegate(context);

            }

            catch (Exception ex)

            {

                await HandleExceptionAsync(context, ex);

            }

        }

 

        private static Task HandleExceptionAsync(HttpContext context, Exception exception)

        {

            var code = HttpStatusCode.InternalServerError;

            var result = JsonConvert.SerializeObject(new { error = exception.Message });

            context.Response.ContentType = "application/json";

            context.Response.StatusCode = (int)code;

            return context.Response.WriteAsync(result);

        }

    }

 

And register the class in Configure method of Startup class:

 

 

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            else

            {

                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();

            }

 

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseCookiePolicy();

 

            app.UseMiddleware(typeof(MiddlewareExceptionHandler));

 

            app.UseMvc(routes =>

            {

                routes.MapRoute(

                    name: "default",

                    template: "{controller=Home}/{action=Index}/{id?}");

            });

        }

 

Note that I'm returning the exception as JSON. In order to Invoke the exception in HTTP, you can change the MiddlewareExceptionHandler class like below:

 

  

 public class MiddlewareExceptionHandler

    {

        private readonly RequestDelegate _requestDelegate;

 

        public MiddlewareExceptionHandler(RequestDelegate requestDelegate)

        {

            _requestDelegate = requestDelegate;

        }

 

        public async Task Invoke(HttpContext context)

        {

            try

            {

                await _requestDelegate(context);

            }

            catch (Exception ex)

            {

                if (context.Response.HasStarted)

                {

                    throw;

                }

 

                await context.Response.WriteAsync(ex.Message);

 

                return;

            }

        }

    }

 

comments powered by Disqus