ASP.NET Core Web API Exception Handling?
The exception handling features support us to deal with the unexpected errors which could arise in our code. We can use the try-catch and finally block in our code to handle the exceptions.
we can extract all the exception handling logic into a single centralized place even when there is nothing wrong with the try-catch block in our Web API project. Doing this, our actions can be made more readable and the error handling process more maintainable.
In this article, we are handling errors by using middleware for global error handling to show the benefits of this approach.
let us begin by creating a custom exception filter class (for my code: GlobalExceptionFilter is custom filter class) by using Interface: IExceptionFilter or IExceptionFilterAsync.
public class GlobalExceptionFilter: IExceptionFilter
{
public void OnException(ExceptionContext context)
{
throw new NotImplementedException();
}
}
Now we must define the OnException method as per our requirements(to handle Exception).
public class GlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
var message = "Internal Server Error ";
var exceptionType = context.Exception.GetType();
if (exceptionType.FullName is "System.IndexOutOfRangeException")//my custom exception type
{
message = context.Exception.Message;
}
context.ExceptionHandled = true;
HttpResponse response = context.HttpContext.Response;
response.StatusCode = (int)status;
response.ContentType = "application/json";
context.Result = new ObjectResult(new ApiResponse() { Message = message, Data = null });
}
}
public class Response
{
public string Message { get; set; }
public object Data { get; set; }
}
In Above example, if an exception is a custom (For demo "IndexOutOfRangeException" is handled) type then we will pull exception message from exception object else we will just send "Internal Server Error " as a general message and at last, we return Response object wrapping by ObjectResult. The response is a class contains two property Message and Data. As shown on Above code, once an Exception was handled, we must set ExceptionHandled Property of ExceptionContext to true.
Now, let us register our " TestExceptionFilter" in ConfigureServices on "Startup.cs", which helps us to handle the exception occur in Web API globally.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(config =>
{
config.Filters.Add(typeof(TestExceptionFilter));
});
}
Let us add controller to test our code, and added two methods.
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
int a = 12;
int c = a / 0;
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public IEnumerable<string> Get(int id)
{
int[] a = new int[] { 1, 2, 3 };
return new string[] { "value1", "value2", a[id].ToString() };
}
}
Let us Run our WebAPI. On URL “http://localhost:65007/api/values”
As previously mentioned, the general message "Internal Server Error " was seen.
Again, on URL “http://localhost:65007/api/values/5”. We can see
Conclusion:
In this article, we learned how to Handle Exception on ASP.NET Core Web API.
Happy Coding!!!