Ads

Web API 9 : Handling the exception in Web API

There are many ways to handle exceptions in ASP.NET Core Web API

Using try catch block we can send the valid error response to the client when error occurs. But problem here is! we need to add try catch everywhere(every API controller action method). Error will not be sent, if we miss to add any of the controller action method.

Then better idea is handling the exception globally.

In this article we will learn how to handle the exception globally in ASP.NET CORE WEB API.

In ASP .NET core, there is a built-in middleware for handling the exception.

What is Middleware?

Middleware is the location, where different types of feature such as Auth, CORS, Versioning, Swagger etc. are separated and executed sequentially in the request processing pipeline. Each middleware has access to request context and can write into the response if required. 

Lets Start Now...

1. Create web API project.

2. Create controller and action method with exception

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using My.Simple.Web.API.Models;

namespace My.Simple.Web.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LearningController : ControllerBase
    {

        [HttpGet("learning-list")]
        public IActionResult Get()
        {
            List<Learning> learningList = new List<Learning>();            

            if(learningList.Count <= 0)
                throw new FormatException();

            return Ok(learningList);
        }
    }
}

Above method we have generated the Error called  FormatException() when there is no data.

3. Lets run the application and hit the URL in swagger or manually.

When we hit the URL, we get below error


Lets Fix this issue:

1. Go to Program.cs and add the below code before app.MapControllers();

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.
    Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;

    await context.Response.WriteAsJsonAsync(new
    {
        title = "Error Occurred",
        description = exception.Message,
        timeOfError = DateTime.Now
    });
}));

IExceptionHandlerPathFeature : 

Interface which helps us to get the end point where error occurred, also gets the original error detail, path of the error and and route value associated with the request.

When we receive error we have create response and send same to the user

 await context.Response.WriteAsJsonAsync(new
    {
        title = "Error Occurred",
        description = exception.Message,
        timeOfError = DateTime.Now
    });


2. Lets run the application now, it should display error message in proper format.


Hit the URL in browser


Yes, its displaying the error message in proper format.

We can display the same in UI.

I hope you enjoyed this article. Post your question in comment section.

Also you can download complete source code here Download Source Code

See you in next article, Take care bye.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !