DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Global Exception Handling In Asp.net Core Web API With Complete Example

In ASP.NET Core Web API, global exception handling allows you to handle unhandled exceptions that occur during the processing of requests. This helps ensure a consistent and user-friendly experience by returning appropriate error responses instead of letting exceptions crash the application. To implement global exception handling, you can use middleware to catch exceptions at a centralized location.

Here's a complete example of how to set up global exception handling in an ASP.NET Core Web API:

Step 1: Create a new ASP.NET Core Web API Project
Start by creating a new ASP.NET Core Web API project. You can do this using the command-line interface (CLI) or by using Visual Studio.

Step 2: Install required NuGet packages
Install the following NuGet packages to handle global exception handling:

dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a custom exception class (Optional)
You can create a custom exception class to represent specific application-level exceptions. This can be useful for adding more context to the errors.

public class CustomException : Exception
{
    public CustomException(string message) : base(message)
    {
    }

    // Add any additional properties or constructors as needed
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Implement global exception handling middleware
Create a new middleware class to handle global exceptions. The middleware will catch unhandled exceptions and convert them into appropriate HTTP responses.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using System.Net;

public class GlobalExceptionMiddleware
{
    public async Task InvokeAsync(HttpContext context, Func<Task> next)
    {
        try
        {
            await next();
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        // Customize the error response as needed
        var response = new
        {
            error = new
            {
                message = "An error occurred while processing your request.",
                details = ex.Message // You can choose to include more details here
            }
        };

        return context.Response.WriteAsync(JsonConvert.SerializeObject(response));
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Register the global exception handling middleware in the Startup.cs file

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    // ... other configuration code ...

    public void ConfigureServices(IServiceCollection services)
    {
        // ... other service configurations ...

        services.AddControllers().AddNewtonsoftJson();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ... other app configurations ...

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/error"); // Replace "/error" with your custom error handling endpoint if needed
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseRouting();

        // Use the custom global exception handling middleware
        app.UseMiddleware<GlobalExceptionMiddleware>();

        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

With these steps, you have implemented global exception handling in your ASP.NET Core Web API. Now, any unhandled exceptions will be caught by the middleware, and an appropriate JSON error response will be returned to the client with a status code of 500 (Internal Server Error).

Remember to adjust the error response message and format as per your application's requirements. Also, consider logging the exceptions for better error tracking and debugging in production environments.

Top comments (0)