ASP.NET Core MVC Interview Question #49

How should exceptions be handled in MVC controllers?

Controllers, Actions, Model Binding & Action Results Junior Beginner

Quick Interview Answer

Controllers should generally not contain repetitive try/catch blocks for every unexpected exception. Centralized exception-handling middleware or an exception handler can log unexpected failures and return an appropriate error response or page.

Detailed Explanation

Controllers should generally not contain repetitive try/catch blocks for every unexpected exception. Centralized exception-handling middleware or an exception handler can log unexpected failures and return an appropriate error response or page.

Controllers can still handle expected application outcomes when they can respond meaningfully, such as validation failures or known business conflicts. Do not expose stack traces or sensitive exception details to production users.

Code Example

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