0

I have a similar problem like it is described here I would like to have a generalized error handling mechanism for the controllers, if an error occurs I would like to display the same view where the error occured with added errors to the ModelState. I have something like this:

        public override void OnException(ExceptionContext filterContext)
    {
        filterContext.Controller.TempData["UnhandledException"] = filterContext.Exception;
        filterContext.ExceptionHandled = true;

        ((Controller)filterContext.Controller).ModelState.AddModelError(
             ((BaseException)filterContext.Exception).Message,
             ((BaseException)filterContext.Exception).StackTrace
         );

        filterContext.Result = new ViewResult
        {
            ViewName = this.View,
            TempData = filterContext.Controller.TempData,
            ViewData = filterContext.Controller.ViewData,

        };


    }

But I am receving null reference exception in Index.cshtml ln. 3 The error message: An exception of type 'System.NullReferenceException' occurred in App_Web_dc1p1y1y.dll but was not handled in user code

the code from my index.cshtml:

@model MyProject.Web.Models.UserProfileViewModel
@{
    ViewBag.Title = "User profile";
 }
 <section>
   <div class="noPadding">
    <div class="col-xs-12 noPadding">
        <h2>My profile</h2>

    </div>  etc....

So I dont want to redirect to some Error view, but I would like to display the error on the samve view where it occured.

What am I doing wrong ?

Community
  • 1
  • 1
  • Where are you expecting these errors to occur? If it is within a `Controller` method, then it will probably not have decided which View will be displayed. You would be better off using a standard `try/catch` block in the controller and using a helper method in the catch to call `AddModelError()` – Rhumborl Oct 08 '14 at 09:32
  • The errors may occure in layers beneath the controller, for instance in called services or when something is saved in the db, not directly in controlers. I would like to avoid try catch in every action... so thats why I am trying to solve this with OnException or filtering .. whatever. – aleksandar1979 Oct 08 '14 at 09:53
  • Probably you are displaying error message as you desired but in `index.cshtml` page `Model` is null and when you are trying to access `MyProject.Web.Models.UserProfileViewModel` properties on page, you got `NullReferenceException`. – Mohsen Esmailpour Oct 08 '14 at 12:24
  • Well that is possible... do you maybe have an idea how to get the model from ExceptionContext filterContext ? and how to provide it via ViewResult ? – aleksandar1979 Oct 08 '14 at 13:22

0 Answers0