How can we do exception handling in MVC?

Answer

In the controller you can override the “OnException” event and set the “Result” to the view name which you want to invoke when error occurs. In the below code you can see we have set the “Result” to a view named as “Error”.

We have also set the exception so that it can be displayed inside the view.

public class HomeController : Controller
 {
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;

     var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");

     filterContext.Result = new ViewResult()
{
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
     };

        }
}

To display the above error in view we can use the below code

  @Model.Exception;

All asp.net-mvc Questions

Ask your interview questions on asp-net-mvc

Write Your comment or Questions if you want the answers on asp-net-mvc from asp-net-mvc Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---