Ehsan Ghanbari

Experience, DotNet, Solutions

Using Middleware to handle exceptions in asp.net core

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;

            }

        }

    }

 

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In asp.net MVC
How to query over Icollection<> of a type with linq
Domain driven design VS model driven architecture
Redis as a cache server
What's the DDD-lite?
comments powered by Disqus