You can use the solution as Mark described above HandleError attrib.
Another solution to catch errors is to have a baseclass the all you controller class derives from. And inside the baseclass ovveride OnException method to show a user friendly error view that you have in for example "~/Shared/Error.aspx"
You also need to have <customErrors mode="On" >
defined in your root web.config for this solution to work.
public class BaseController : Controller
{
ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public BaseController()
{
}
protected override void OnException(ExceptionContext filterContext)
{
// Log the error that occurred.
log.Fatal("Generic Error occured",filterContext.Exception);
// Output a nice error page
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
View("Error").ExecuteResult(ControllerContext);
}
}
}
Above solution catches most of the possible "yellow screen of death errors" that occurs.
To handle other errors like 404 i use folowing mapRoute last in global.asax RegisterRoutes(RouteCollection routes)
// Show a 404 error page for anything else.
routes.MapRoute(
"Error",
"{*url}",
new { controller = "Shared", action = "Error" }
);