MVC Developer Question:

Download Job Interview Questions and Answers PDF

Tell me how can we do exception handling in MVC?

MVC Developer Interview Question
MVC Developer Interview Question

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;

Download MVC Developer Interview Questions And Answers PDF

Previous QuestionNext Question
Tell us what are the advantages of ASP.NET MVC?Tell us what is ViewStart?