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
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
});
}));
await context.Response.WriteAsJsonAsync(new
{
title = "Error Occurred",
description = exception.Message,
timeOfError = DateTime.Now
});