Using the HandleError attribute is the way to go. Here is a small sample which I use to handle Ajax calls from JQuery, ExtJs, and others.
On your controller
public class DataController : Controller
{
[HandleError(ExceptionType = typeof(ArgumentException), View = "ErrorAjax")]
public void Foo(string x, string y)
{
if (String.IsNullorEmpty(x))
throw new ArgumentException("String cannot be empty!");
// Call your layers or whatever here
AnotherCall();
}
}
Then on your view (ErrorAjax). Notice it's strongly typed (HandleErrorInfo)
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HandleErrorInfo>" %>
<!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>Sorry Dude!</title>
</head>
<body>
<div>
<!-- be creative here-->
Sorry, an error occurred while processing your request.
Action = <%= ViewData.Model.ActionName %>
Controller = <%= ViewData.Model.ControllerName %>
Message = <%= ViewData.Model.Exception.Message %>
</div>
</body>
</html>
A couple of gotchas
- Check your web.config and make sure customErrors mode="On"
- For starters, create the View under the Shared folder