global error handling and logging
Loading
global error handling and logging
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Raghunath BhukanRank #744 · 3.1K reputationPosted Jan 21, 2026, 6:56 AM EST
Practical explanation of how to implement global error handling and logging in ASP.NET Core, covering both the mechanism (middleware) and best practices for logging exceptions.
What Global Error Handling Means
Global error handling lets your app catch and manage exceptions in one central place, rather than scattering
try-catchblocks all over controllers, actions, or services. In ASP.NET Core, this is typically done using middleware that intercepts all unhandled exceptions early in the request pipeline. This approach keeps your API clean, maintainable, and consistent in how it responds to errors.Logging in ASP.NET Core
ASP.NET Core comes with a built-in logging abstraction (
ILogger) that works with multiple providers (console, debug, file, Serilog, NLog, Application Insights, etc.). You use this to log exceptions and related context so you can diagnose issues later.How to Implement Global Error Handling and Logging
Step 1: Configure Built-in Logging Providers
In
Program.cs, configure logging when the app starts:var builder = WebApplication.CreateBuilder(args); // Configure built-in logging providers builder.Logging.ClearProviders(); builder.Logging.AddConsole(); builder.Logging.AddDebug(); // Add others like Application Insights, Serilog, etc. var app = builder.Build();The
ILoggerinterface is automatically available via DI once logging is configured.Step 2: Add a Custom Global Exception Handling Middleware
Create a custom middleware that catches exceptions, logs them, and returns a consistent error response:
public class ErrorHandlerMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public ErrorHandlerMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { try { await _next(context); // Call next middleware } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception occurred."); // Log error context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/json"; var result = JsonSerializer.Serialize(new { message = "An unexpected error occurred. Try again later." }); await context.Response.WriteAsync(result); } } }This middleware:
Catches any unhandled exception in the pipeline.
Logs it using
ILogger.Sends back a consistent JSON error response.
Step 3: Register the Middleware Early in the Pipeline
In
Program.cs, register the middleware before other middleware that might handle requests:This ensures it wraps all subsequent request processing, catching exceptions anywhere downstream.
Step 4: Use Standard Middleware for Error Pages in MVC (Optional)
If you’re building an MVC app and want custom views for errors, you can use the built-in exception handler:
if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // Redirect to an error route } else { app.UseDeveloperExceptionPage(); // Detailed error page in dev }Here, the error route (
/Home/Error) can access exception details viaIExceptionHandlerPathFeatureif needed.Logging Exceptions with
ILoggerAnywhere in your controllers/services, you can log at different levels:
public class UsersController : ControllerBase { private readonly ILogger _logger; public UsersController(ILogger logger) { _logger = logger; } [HttpGet] public IActionResult Get() { try { // Some code } catch (Exception ex) { _logger.LogError(ex, "Error fetching users"); // Structured logging throw; // Let global handler pick it up } return Ok(); } }You decide what to catch locally vs. what to allow the global handler to manage.
Best Practices Around Error Handling and Logging
Don’t expose sensitive info in production responses. Return generic messages while logging detailed info internally.
Use structured logging. ILogger supports structured logs that make filtering easier in tools like Splunk or Elastic.
Use appropriate log levels. Log exceptions typically at
ErrororCritical.Use correlation IDs to trace logs across distributed systems.
Don’t overuse try-catch in every method. Let middleware handle unexpected exceptions; catch only when you want to return specific HTTP responses.
Steps Summary
Configure logging providers (
ILogger).Implement global exception handling using custom middleware.
Register it early in the pipeline.
Catch and log exceptions, return structured error responses.
Apply best practices for security and observability.
Jignesh KumarRank #91 · 22.9K reputationPosted Jan 21, 2026, 10:06 PM EST
Hello Mohan veer singh,
If you are using .net core than best way to implement logging is using middleware.
Centralized global exception handling + structured logging (Serilog)
Global Exception Handling (Single Place)
Register middleware (Program.cs)
app.UseMiddleware();
Structured Logging (Serilog – Recommended)
Install packages
Configure Serilog (Program.cs)
Log the Right Things (Not Everything)