ASP.NET Core MVC Intermediate

Handling errors

Errors will happen. What matters is that users see a friendly page, you get the details in your logs, and nothing sensitive leaks. This lesson covers the developer exception page, the exception handler middleware, status code pages and the Error action.

What happens when an action throws
  1. StartAn exception is thrownFor example the database is unavailable
  2. Step 2It bubbles upThrough filters and middleware towards the start of the pipeline
  3. Step 3Exception handler catches itUseExceptionHandler, added first in Program.cs
  4. Step 4It is loggedWith the stack trace and request id
  5. Step 5Request is re-executedThe pipeline runs again for /Home/Error
  6. EndUser sees a friendly pageStatus 500 with a request id, no stack trace

The idea in plain words

In Development, ASP.NET Core shows the developer exception page with the stack trace, which is exactly what you want while coding and exactly what you must never show the public. In other environments, UseExceptionHandler catches unhandled exceptions, logs them and re-runs the request against an error path, so users get a normal page.

Not every problem is an exception. A missing page returns 404 with an empty body; status code pages middleware turns those into friendly pages as well.

Example: Program.cs

The exception handler goes first so it can catch errors from everything after it.

C#
var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/Home/Status/{0}");

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

Example: the error actions

C#
public class HomeController : Controller
{
    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        _logger.LogError(feature?.Error, "Unhandled error on {Path}", feature?.Path);
        return View(new ErrorViewModel { RequestId = HttpContext.TraceIdentifier });
    }

    public IActionResult Status(int code)
        => View(code == 404 ? "NotFound" : "Status", code);
}

Common mistakes

  • Showing the developer exception page or ex.Message to real users.
  • Wrapping every action in try/catch and swallowing errors; let the global handler deal with unexpected exceptions.
  • Putting UseExceptionHandler after other middleware, so it cannot catch their errors.
  • Forgetting to log, so users see a friendly page and nobody knows something broke.

Interview question

How do you implement global exception handling in ASP.NET Core?

Add UseExceptionHandler early in the middleware pipeline, pointing to an error path or a lambda, so unhandled exceptions from later middleware and MVC are caught, logged and turned into a safe response. Since .NET 8 you can also register IExceptionHandler implementations to handle specific exception types centrally. Exception filters can handle MVC-specific cases, but middleware covers the whole app.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.