Like any other programming language in asp.net framework we have some standard ways of handling error messages, there are different type of exception can happen in application, here we see how to handle exceptions, error handling best practices in Asp.net MVC Application.
Exception handling example in Asp.net MVC is one of the important tasks in Application development;
Exception can occur for various reasons; here is few reasons that cause an exception.
We write code inside the try block that may potentially throw an exception.
Inside catch block codes written for handling the exception, so the exception does not terminate the application, also this is the place where we can call all type of error logging methods
Using throw keyword we can throw the current exception or can throw a new exception with custom message
Most of the developer don’t write this finally block, this block is always executed whether any exception occur or not, so if you need anything to be executed at last, this is the place to call the method
Here we see all best practice in error handing with example.
Common way error handling exception is using try catch in your method or function
public ActionResult errorhandling() { try { // here is your functional coding, database call etc. } catch (Exception ex) { // if anything goes wrong } finally { } return View(); }
We can implement error handling in Global.Asax, just by writing few lines code in Application_Error
protected void Application_Error(object sender, EventArgs e) { Exception exception = Server.GetLastError(); // Here you can log / email exception details Server.ClearError(); // clear error & redirect to a common page Response.Redirect("CommonErrorPage"); }
Handling HTTP errors in Asp.net MVC
Implement error handling in web.Config, just by coniguring "customErrors" tag
<system.web> <customErrors mode="On" defaultRedirect="CommonErrorPage"> <error statusCode="404" redirect="~/CommonErrorPage/NoPageFound"/> </customErrors> </system.web>
HandleErrorAttribute class under System.Web.Mvc namespace
public class MyAppError : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { string _errorBaseInfo = null; if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { error = true, message = filterContext.Exception.Message } }; _errorBaseInfo = filterContext.Exception.Message; } else { var controllerName = (string)filterContext.RouteData.Values["controller"]; var actionName = (string)filterContext.RouteData.Values["action"]; var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); filterContext.Result = new ViewResult { ViewName = View, MasterName = Master, ViewData = new ViewDataDictionary(model), TempData = filterContext.Controller.TempData }; _errorBaseInfo = string.Format("controllerName={0} actionName={1} error={2}", controllerName, actionName, filterContext.Exception.Message); } LogError(filterContext.Exception.Message, filterContext.Exception); filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; base.OnException(filterContext); } void LogError(string errorMessage, Exception ex) { //ErrorDTO.TrackError(errorMessage, ex); } }
Now you can use above attribute in any action like code below
[MyAppError] public ActionResult myTestView() { return View(); }
Personally I don’t like this way of error handling, though it provide some built-in features like ArgumentOutOfRangeException , NotImplementedException etc
[HandleError] public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } // We also can write with exception type [HandleError(ExceptionType = typeof(ArgumentOutOfRangeException), View = "someDifferentView")] [HandleError(ExceptionType = typeof(NotImplementedException), View = "myCommonError")] public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); }
We also can Override “OnException” method in controller level , though not very attractive.
public class HomeController : Controller { protected override void OnException(ExceptionContext filterContext) { Exception ex = filterContext.Exception; filterContext.ExceptionHandled = true; var model = new HandleErrorInfo(filterContext.Exception, "myController", "myErrorPage"); filterContext.Result = new ViewResult() { ViewName = "Error", ViewData = new ViewDataDictionary(model) }; } }
Hope you understood all different ways of exception handling in asp.net mvc application.