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):

LevelHow
Codetry/catch in event handlers
PagePage_Error → Server.GetLastError(), Server.ClearError()
ApplicationApplication_Error in Global.asax — log everything unhandled
Configuration`<customErrors mode="On
ToolsELMAH (logs + viewer at /elmah.axd), log4net/NLog

MVC 5:

LevelHow
Actiontry/catch
ControllerOverride OnException(ExceptionContext filterContext)
Filter[HandleError(ExceptionType = ..., View = "Error")], custom IExceptionFilter, global via FilterConfig
ApplicationApplication_Error (catches routing 404s and non-MVC errors)
ConfigurationcustomErrors + 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());