Error & Exception Handling Middleware in ASP.NET Core

>

πŸ’‘ Concept Name

Error & Exception Handling Middleware

πŸ“˜ Quick Intro

Exception handling middleware allows us to catch errors globally in ASP.NET Core. It helps return friendly error messages or redirect to custom error pages. Without it, unhandled exceptions may expose stack traces to users.

🧠 Analogy / Short Story

Think of your app as a restaurant. If the kitchen burns a dish (error), the waiter doesn’t panic. Instead, the manager (error handler middleware) steps in, apologizes, and offers a free dessert (custom response). The customer never sees the kitchen chaos.

πŸ”§ Technical Explanation

In ASP.NET Core, `UseExceptionHandler()` and `UseDeveloperExceptionPage()` are the key middleware for error handling. The developer page is used in development for detailed errors. `UseExceptionHandler()` handles exceptions globally in production environments and lets you customize error responses. It should be added early in the middleware pipeline.

🎯 Purpose & Use Case

  • βœ… Prevent app crashes due to unhandled exceptions
  • βœ… Customize error responses (e.g., JSON, custom pages)
  • βœ… Protect internal details from users (stack traces)
  • βœ… Enable centralized logging of exceptions
  • βœ… Improve developer experience with detailed errors in dev

πŸ’» Real Code Example

// In Program.cs or Startup.cs
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

// ErrorController.cs
public class HomeController : Controller
{
    [Route(""/Home/Error"")]
    public IActionResult Error()
    {
        return View();
    }
}

❓ Interview Q&A

Q1: What is UseExceptionHandler middleware?
A: It catches unhandled exceptions and provides a custom error pipeline.

Q2: What is UseDeveloperExceptionPage for?
A: Shows detailed error info during development.

Q3: Where should exception handling middleware be placed?
A: As early as possible in the pipeline.

Q4: Can you log errors in exception middleware?
A: Yes, you can inject ILogger and log exceptions.

Q5: What if error occurs in static file middleware?
A: Exception middleware can still catch it if placed early.

Q6: What happens without exception middleware?
A: App may crash or expose technical details to users.

Q7: Can we show JSON error responses?
A: Yes, by customizing the response in the handler route.

Q8: Is try-catch still needed with middleware?
A: Yes, for fine-grained exception handling at method level.

Q9: What’s the default error status code?
A: 500 Internal Server Error.

Q10: Can we redirect to error page?
A: Yes, using `app.UseExceptionHandler("/ErrorPage")`.

πŸ“ MCQs

Q1. Which middleware catches unhandled exceptions globally?

  • UseRouting
  • UseEndpoints
  • UseExceptionHandler
  • UseHttpsRedirection

Q2. What is used for showing detailed errors in development?

  • UseExceptionHandler
  • UseStatusCodePages
  • UseDeveloperExceptionPage
  • TryCatch

Q3. Where should error middleware be placed?

  • End of pipeline
  • After endpoints
  • Early in pipeline
  • Before routing

Q4. What is the default error status code?

  • 200
  • 404
  • 301
  • 500

Q5. What does UseExceptionHandler do?

  • Logs requests
  • Handles routing
  • Handles static files
  • Handles unhandled exceptions

Q6. What happens without exception middleware?

  • Nothing
  • Improved security
  • App may expose stack trace
  • Better speed

Q7. Can we log inside exception middleware?

  • No
  • Yes
  • Only in dev
  • Only in production

Q8. What is the route used in UseExceptionHandler?

  • Startup.cs
  • Middleware.cs
  • Custom error endpoint
  • LoggerFactory.cs

Q9. What should be returned from error action?

  • Nothing
  • 404
  • Redirect
  • View or JSON response

Q10. Does try-catch replace exception middleware?

  • Yes
  • No, both are needed
  • Sometimes
  • Only in MVC

πŸ’‘ Bonus Insight

Exception handling middleware is your global safety net. For APIs, you can return standardized JSON error responses using `ProblemDetails`. Always log exceptions before returning user-friendly messages to avoid debugging pain later.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: