public class HomeController : Controller { public ActionResult Index() { try { // code that may throw an exception } catch (Exception ex) { var exceptionContext = new ExceptionContext(this.ControllerContext, ex); HandleException(exceptionContext); } return View(); } public void HandleException(ExceptionContext context) { // custom error handling logic goes here } }
public class CustomHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { var exception = filterContext.Exception; var httpException = exception as HttpException; if (httpException != null) { // custom error handling logic for HTTP exceptions } else { // custom error handling logic for other types of exceptions } filterContext.ExceptionHandled = true; filterContext.Result = new ViewResult { ViewName = "Error" }; } }This example shows how the ExceptionContext class can be used inside a custom HandleErrorAttribute to handle exceptions thrown by an ASP.NET MVC application. The OnException method checks the type of exception that was thrown and performs custom error handling logic based on the exception type. It also sets the ExceptionHandled property to true and specifies a ViewResult that displays an error message to the user. Package library: System.Web.Mvc (part of the Microsoft.AspNet.Mvc NuGet package)