---
title: "How to handle Exception globally in .NET Core?"  
description: "How to handle Exception globally in .NET Core?"  
author: "Anubhav Sharma"  
published: 2026-03-16  
updated: 2026-03-23  
canonical: https://www.mindstick.com/forum/162065/how-to-handle-exception-globally-in-dot-net-core  
category: "asp.net core"  
tags: ["asp.net core"]  
reading_time: 3 minutes  

---

# How to handle Exception globally in .NET Core?

**How to [handle](https://www.mindstick.com/articles/311004/suede-skillet-handle-cover) [Exception](https://www.mindstick.com/articles/1824/objective-c-exception-handling) globally in .NET Core?**

## Replies

### Reply by Ravi Vishwakarma

Global Exception Handling in **.NET Core** is used to catch all unhandled errors in one place instead of writing `try-catch` in every controller or service.

In **ASP.NET Core**, we can handle exceptions globally using:

- Middleware (Best way)
- UseExceptionHandler()
- Custom Exception Middleware
- Filters (MVC)

This article explains **best practice for production**.

## 1. Why Global Exception Handling?

Without global handling:

```cs
try
{
}
catch
{
}
```

in every method → bad practice.

Problems:

- Duplicate code
- Hard to maintain
- Hard to log errors
- Not production safe

Global handling solves this.

- Centralized
- Clean code
- Logging friendly
- Production ready

## 2. Method 1 — UseExceptionHandler (Simple Way)

In `Program.cs`

```cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseExceptionHandler("/Home/Error");

app.Run();
```

Controller:

```cs
public class HomeController : Controller
{
    public IActionResult Error()
    {
        return View();
    }
}
```

This catches all unhandled exceptions.

Good for UI apps.

## 3. Method 2 — Global Exception Middleware (Best Practice)

Best for API / large system.

### Step 1 — Create Middleware

```cs
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)
        {
            await HandleException(context, ex);
        }
    }

    private Task HandleException(HttpContext context, Exception ex)
    {
        context.Response.StatusCode = 500;
        context.Response.ContentType = "application/json";

        var result = new
        {
            Message = ex.Message
        };

        return context.Response.WriteAsJsonAsync(result);
    }
}
```

### Step 2 — Extension Method

```cs
public static class ExceptionMiddlewareExtension
{
    public static IApplicationBuilder UseGlobalException(
        this IApplicationBuilder app)
    {
        return app.UseMiddleware<ExceptionMiddleware>();
    }
}
```

### Step 3 — Register in Program.cs

```cs
var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.UseGlobalException();

app.Run();
```

Now all exceptions handled globally.

## 4. Method 3 — With Logging (Recommended)

Production apps must log error.

```cs
private readonly ILogger<ExceptionMiddleware> _logger;

public ExceptionMiddleware(
    RequestDelegate next,
    ILogger<ExceptionMiddleware> logger)
{
    _next = next;
    _logger = logger;
}
```

```cs
_logger.LogError(ex, ex.Message);
```

Best practice.

## 5. Return Proper Status Code

```cs
if (ex is KeyNotFoundException)
    status = 404;
else
    status = 500;
```

Good API design.

## 6. Method 4 — Using Filter (MVC Only)

```cs
public class GlobalExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        context.Result = new ObjectResult("Error")
        {
            StatusCode = 500
        };
    }
}
```

Register:

```cs
builder.Services.AddControllers(options =>
{
    options.Filters.Add<GlobalExceptionFilter>();
});
```

## 7. Best Practice (Interview Answer)

Use:

- Middleware
- Logging
- Custom response
- Status code handling
- No try-catch everywhere

Best for large system.

## 8. Conclusion

Global exception handling in .NET Core should be done using:

- Custom Middleware
- Logging
- Proper status codes
- Clean response

This is production-level approach.


---

Original Source: https://www.mindstick.com/forum/162065/how-to-handle-exception-globally-in-dot-net-core

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
