ASP.Net MVC Framework - Exception Handling
Note: This post is based on an early preview version of the ASP.Net MVC Framework and much will happen until the next milestone.
In this post I will show how we can handle errors that occur in a Controller’s Action method.
The Controller base class has a virtual method with the name OnError, this method takes three arguments, actionName, methodInfo and exception. It also has a return type of a Boolean. The idea when using the OnError method is to return true if we have handled the exception or false to letting ASP.Net handle it for us.
protected virtual bool OnError(string actionName, System.Reflection.MethodInfo methodInfo, Exception exception)
When an exception is thrown within our Action method, the OnError method will be executed. In the OnError method we can for example pass information to a View.
Here is an example of a Controller where I will Render a View called “Error” and pass the exception to the View:
public class HomeController : Controller
{
protected override bool OnError(string actionName, System.Reflection.MethodInfo methodInfo, Exception exception)
{
RenderView("Error",exception.InnerException);
return false;
}
[ControllerAction]
public void Index()
{
int i = 0;
int sum = 10 / i;
RenderView("Index");
}
}
When the Index Action method will be executed a DevidedByZero Exception will be thrown, when this happens the OnError method will be called and it will render a view and return false to specify that the error was handled.
To make sure to have a common View for displaying the error message, we put it into the Shared subfolder of the Views folder:
/Views
/Shared
Error.aspx
The Error View inherits the ViewData<Exception> class. To make this demo simple I just pass the Exception class to the View and show the value of the Message property:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Error.aspx.cs" Inherits="MvcApplication.Views.Error" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<div>
<h1>Error on page</h1>
<b><%=ViewData.Message %></b>
</div>
</body>
</html>