Roadmap › Exception Handling & Custom Error Handling in .NET — Every Way, Every App Type › Module: Error Handling by Application Type
Lessons in this course (9)
5. ASP.NET Web Forms and MVC 5 (.NET Framework)
Intermediate★ Must knowLesson 5 of 9
Web Forms (from local to global):
| Level | How |
|---|---|
| Code | try/catch in event handlers |
| Page | Page_Error → Server.GetLastError(), Server.ClearError() |
| Application | Application_Error in Global.asax — log everything unhandled |
| Configuration | `<customErrors mode="On |
| Tools | ELMAH (logs + viewer at /elmah.axd), log4net/NLog |
MVC 5:
| Level | How |
|---|---|
| Action | try/catch |
| Controller | Override OnException(ExceptionContext filterContext) |
| Filter | [HandleError(ExceptionType = ..., View = "Error")], custom IExceptionFilter, global via FilterConfig |
| Application | Application_Error (catches routing 404s and non-MVC errors) |
| Configuration | customErrors + httpErrors |
Web API 2: ExceptionFilterAttribute (per controller/action), global IExceptionHandler (one place to shape the response) and IExceptionLogger (many loggers), HttpResponseException / Request.CreateErrorResponse for explicit status codes.
csharp
public class ApiExceptionHandler : ExceptionHandler // Web API 2
{
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError,
new { error = "An unexpected error occurred.", correlationId = context.Request.GetCorrelationId() }));
}
}
config.Services.Replace(typeof(IExceptionHandler), new ApiExceptionHandler());