DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on • Edited on

Exception Handling in ASP.NET Core Web API

Capturing and managing exceptions that arise during the execution of HTTP requests is the responsibility of exception handling in the ASP.NET Core Web API. It enables you to manage exceptions in a centralized manner and give customers meaningful error answers. To handle errors in the ASP.NET Core Web API, follow these steps:

1. Global Exception Handling:

Implementing a global exception handler that catches any unhandled exceptions happening while the API is being used is one strategy. You can achieve this by developing a unique middleware component that detects errors and produces suitable answers. Here's an illustration:

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            // Handle the exception and generate a response
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        // Generate an error response based on the exception
        var response = new { error = exception.Message };
        var payload = JsonConvert.SerializeObject(response);
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return context.Response.WriteAsync(payload);
    }
}
Enter fullscreen mode Exit fullscreen mode

To register the middleware globally, add the following line to the Configure method in your Startup.cs file:

app.UseMiddleware<ExceptionMiddleware>();
Enter fullscreen mode Exit fullscreen mode

2. Exception Filters:

Utilizing exception filters, which let you handle exceptions for actions or controllers, is a different strategy. Implementing the "IExceptionFilter" interface allows you to make your own exception filter. As an illustration, consider the following.

public class CustomExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        // Handle the exception and generate a response
        var response = new { error = context.Exception.Message };
        var payload = JsonConvert.SerializeObject(response);
        context.Result = new ContentResult
        {
            Content = payload,
            ContentType = "application/json",
            StatusCode = (int)HttpStatusCode.InternalServerError
        };
        context.ExceptionHandled = true;
    }
}
Enter fullscreen mode Exit fullscreen mode

To apply the filter to a specific action or controller, use the [ServiceFilter] attribute:

[ServiceFilter(typeof(CustomExceptionFilter))]
public class MyController : ControllerBase
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

3. Custom Exception Types:

To describe particular problem circumstances in your API, you may also construct your own exception classes. You can handle these custom exceptions by throwing them and providing detailed error answers by utilizing the methods discussed above. As an illustration, consider the following.

public class NotFoundException : Exception
{
    public NotFoundException(string message) : base(message)
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

In your action or middleware, you can throw the custom exception when needed:

throw new NotFoundException("The requested resource was not found.");
Enter fullscreen mode Exit fullscreen mode

These are some typical methods used in the ASP.NET Core Web API to manage errors. You can pick the one that best suits the needs and error-handling technique of your application.

Top comments (0)