In this article, we will explain using Override onException method handling an exception in ASP.NET MVC with example.

In this method we can override the “OnException” event of the controller and set the “Result” to the view name. This view gets invoked when error occurs in this controller.

In this case, we must intimate the filtercontext that we have handled the error. For this, we need to write the below line of code.

filterContext.ExceptionHandled= true;

In the below code you can see we have set the “Result” to a view named as “Error”.

      public ActionResult Index()
            var queryString = Request.QueryString["myquery"].ToString();
            return View();
        protected override void OnException(ExceptionContext filterContext)
            ViewResult view = new ViewResult();
            view.ViewName = "Error";
            filterContext.Result = view;
            filterContext.ExceptionHandled = true;

Now, in the above scenarios, we will have to handle the exception on the controller  base.  When error comes in any method in this controller then execute “OnException” method. In this method you can create log file or save in database to error message and redirect to error view.

In above example when we execute index method without “myqueryQueryString then it will occurs error and execute OnException method.

I hope you will use it after reading.


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like