Global Exception Handling in ASP.NET Core WEB API

By | July 11, 2017

In my previous post, I have used multiple ways (Exception filter, Global.asax, OnException at Controller etc.,) to implement exception handling in Asp.Net MVC.

Asp.Net Core comes with many in-built and ready to use middleware, and you can add them to your application in the Startup class Configure method. One of the in-bulit ASP.NET Core diagnostic middleware is UseExceptionHandler which will be used in this post to implement exception handling globally. UseExceptionHandler can be used to handle exceptions globally. You can get all the details of exception object like Stack Trace, Inner exception and others.

First create model class for error object as below.

public class ErrorDto
    {
        public int Code { get; set; }
        public string Message { get; set; }

        // other fields

        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }

Now, you can easily implement like this.

            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {

                    // or another Status accordingly to Exception Type
                    context.Response.StatusCode = 500; 
                    context.Response.ContentType = "application/json";

                    var error = context.Features.Get();
                    if (error != null)
                    {
                        var ex = error.Error;
                        //Write as in a log file
                       //System.IO.File.WriteAllText(@"exception.txt", ex);

                        await context.Response.WriteAsync(new ErrorDto()
                        {
                            Code = 500,
                            Message = ex.Message // or your custom message
                            // other custom data
                        }.ToString(), Encoding.UTF8);
                    }
                });
            });

You need to put this code inside configure() method of startup.cs file as below.

Now let’s throw some exception. I am using DivideByZeroException exception as below.

[Route("api/Default")]
    public class DefaultController : Controller
    {
        public IActionResult Get()
        {
            int i = 10;
            int k = 0;
            int result = i / k;
            return Ok();
        }

    }

Now, Run the application and hit url via postman as shown below. You can also debug it and check in case of exception, it will hit the app.UseExceptionHandler() code.

 

I hope you will enjoy the Global Exception Handling in ASP.NET Core WEB API. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Like it? Share it