Search code examples
asp.net-mvcexceptionrazorengine

Catching Exceptions in the Controller


It seems like if an Exception occurs inside a controller, the view-engine won't go to the intended view, even if the "exception" is caught inside a try-catch block?

or I'm missing something here:

public ActionResult MyController(int? param1, DateTime? param2)
{
    MyModel model = new MyModel();
    try
    {
        model = new MyModel();

        //AN ERROR HAPPENS HERE (so the code goes to catch the Exception):
        model.Connection.Initialize();
    }
    catch (Exception ex)
    {
        ViewBag.ErrorMessage = ex.Message;
    }
    //when I put a break point I get to this following line, however, "MyView" is never displayed!?
    return PartialView("MyView", model);
}

Solution

  • You might be getting another exception afterwards, somewhere in your view. Look at the stack trace that displays on the browser page and fix that.