4

I'm developing ASP.NET MVC application, for handling error, I followed this tutorial. So, code in the FilterConfig.cs:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new CustomHandleErrorAttribute());
}

I added a ErrorController in Controllers folder:

public class ErrorController : Controller
{
    // GET: Error
    public ActionResult Index()
    {
        return View();
    }
}

I also created the View to display the error in Views/Error:

@model System.Web.Mvc.HandleErrorInfo

@{
    ViewBag.Title = "Index";
}

<h1 class="text-danger">Custom Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

<h2>Exception details</h2>
<p>
    Controller: @Model.ControllerName <br />
    Action: @Model.ActionName<br />
    Message: @Model.Exception.Message <br />
    StackTrace: <br />
</p>
<pre>Exception: @Model.Exception.StackTrace</pre>

Then I created Admin Area and moved all the admin's views to Admin folder. Admin Area has its layout, it's different with main layout.

For handling error in Admin Area, I also created ErrorController.cs in ~/Areas/Admin/Controllers and its View in ~/Areas/Admin/Views/Error to show error in admin's layout, but when the error occur on admin's page. It will display the message in main layout (~/Views/Error)

How to handle error for each areas in MVC?

CustomErrorHandlerAttribute.cs

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        //base.OnException(filterContext);

        // Log the error using Elmah & NLog
        if (filterContext.Exception is DbEntityValidationException)
        {
            DbEntityValidationException dbevex = filterContext.Exception as DbEntityValidationException;

            var errorMessages = (from eve in dbevex.EntityValidationErrors
                                 let entity = eve.Entry.Entity.GetType().Name
                                 from ev in eve.ValidationErrors
                                 select new
                                 {
                                     Entity = entity,
                                     PropertyName = ev.PropertyName,
                                     ErrorMessage = ev.ErrorMessage
                                 });

            var fullErrorMessage = string.Join("; ", errorMessages.Select(e => string.Format("[Entity: {0}, Property: {1}] {2}", e.Entity, e.PropertyName, e.ErrorMessage)));
            var exceptionMessage = string.Concat(dbevex.Message, " The validation errors are: ", fullErrorMessage);
            LogUtility.logger.Error(exceptionMessage);
            ErrorSignal.FromCurrentContext().Raise(new DbEntityValidationException(exceptionMessage, dbevex.EntityValidationErrors));
        }
        else
        {
            LogUtility.logger.Error(filterContext.Exception.Message, filterContext.Exception);
        }

        if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
        {
            return;
        }
        if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
        {
            return;
        }
        if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
        {
            return;
        }

        // If the request is AJAX return JSON else view
        if (filterContext.HttpContext.Request.IsAjaxRequest()) //if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            // Because it's exception raised after ajax invocation, return Json
            filterContext.Result = new JsonResult
            {
                Data = new
                {
                    error = true,
                    message = filterContext.Exception.Message
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName = (string)filterContext.RouteData.Values["action"];
            var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

            filterContext.Result = new ViewResult()
            {
                ViewName = View,
                MasterName = Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
        }

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 500;
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // Visual Studio 2013 Browser Link caused
        // "The controller for path '/9ac086a69364466a841e03e001f946fd/arterySignalR/ping' could not be found."
#if DEBUG
        routes.IgnoreRoute("{*browserlink}", new { browserlink = @".*/arterySignalR/ping" });
#endif
        // with code above, we can still use Browser Link feature without getting error

        routes.MapRoute(
           "AxCustomer",
           "AxCustomer/{action}/{id}",
           new { controller = "AX_CUSTTABLE", action = "Index", id = UrlParameter.Optional },
           namespaces: new[] { "SalesSupportSystem.Controllers" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "SalesSupportSystem.Controllers" }
        );
    }
}
Willy
  • 1,689
  • 7
  • 36
  • 79

1 Answers1

0

This is untested, but have you tried specifying the Admin area in filterContext.RouteData.Values["area"] = "Admin"; before setting filterContext.Result?

Like this:

filterContext.RouteData.Values["area"] = "Admin";
filterContext.Result = new ViewResult()
...
Joseph Woodward
  • 9,191
  • 5
  • 44
  • 63