0

What can i do to catch rendering exceptions in mvc? (I am using 1st version)

I started from worth case scenario - compile time error in .ascx file and here is what i discovered:

1) In debug mode, visual studio says there is unhandled exception in Controller.ExecuteCore(), InvokeAction line:

try {
      string actionName = RouteData.GetRequiredString("action");
      if (!ActionInvoker.InvokeAction(ControllerContext, actionName)) { // this line
          HandleUnknownAction(actionName);
     }
}
finally {
   TempData.Save(ControllerContext, TempDataProvider);
}

2) Application.OnError is not called

3) Controller.OnError is not called

4) when I injected catch() here it is also not triggered.

5) try.. catch in masterpage doesn't triggered (althrough it present in stacktrace!)

6) try.. catch in page doesn't triggered (it also present in stacktrace!)

I was able to catch exception only when I wrapped specific RenderPartial method, like this:

<% try
   { %>
    <%Html.RenderPartial("Search/" + Model.SearchCategory + "SearchList", Model); %>
    <%}
   catch (Exception ex)
   { %><% HttpContext.Current.Response.Redirect("/en/App/Error"); %><% } %>

And what i can do than?

  • I cannot return RedirectAction because we are not in controller
  • I try HttpContext.Current.Response.Redirect but it is not really working (I am having page with text: Object moved to .)
st78
  • 8,028
  • 11
  • 49
  • 68

2 Answers2

0

Not sure if this will help, but have you tried turning ON the MvcBuildViews option in the project? As I understand it (and I'm still learning MVC myself), views are compiled "on demand", not when the project is built. This may show previously undetected errors. The setting is turned OFF by default.

To turn it on, unload the project in VS, open the project file and change the MvcBuildViews option to "true" in the XML. Then reload the project.

James Allen
  • 819
  • 7
  • 12
  • This question also has details on the MvcBuildViews option: [link](http://stackoverflow.com/questions/383192/compile-views-in-asp-net-mvc) – James Allen Apr 10 '11 at 22:52
  • Thanks for your comment. I just verified, behaviour is the same also with other exceptions, such as NUllReferenceException – st78 Apr 10 '11 at 23:19
0

Take a look at using a filter attribute to catch this behavior.

For example:

public class CustomAttribute : ActionFilterAttribute
{
      public override void OnResultExecuted(ResultExecutedContext filterContext)
      {
           if(filterContext.Exception != null)
           {
                //YOU SHOULD BE ABLE TO SEE YOUR EXCEPTION HERE. 
                Trace.WriteLine(Exception.Message);
           }
       }
}

Then just decorate your controller class with [CustomAttribute]

[CustomAttribute]
public class SomeController : Controller
{
 //Controller stuff
}

You have a few other overrides available to you, so take a look.

BZink
  • 7,687
  • 10
  • 37
  • 55