How to show exception message in general view of Error.cshtml?

If I start with a new MVC 5 project, in the web.config setting, the customErrors = "on" mode allows the general "Error.cshtml" view to show when I force (raise) an exception, but it only shows the following text ...

Error.

There was an error processing your request.

How do I pass information to this view to display more relevant information, for example, what kind of error? Can I use this view if I use the Global.asax method ...

protected void Application_Error()

?

+4
source share
1 answer

Override filter:

// In your App_Start folder
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ErrorFilter());
        filters.Add(new HandleErrorAttribute());
        filters.Add(new SessionFilter());
    }
}

// In your filters folder (create this)
public class ErrorFilter : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
    {
        System.Exception exception = filterContext.Exception;
        string controller = filterContext.RouteData.Values["controller"].ToString();;
        string action = filterContext.RouteData.Values["action"].ToString();

        if (filterContext.ExceptionHandled)
        {
            return;
        }
        else
        {
            // Determine the return type of the action
            string actionName = filterContext.RouteData.Values["action"].ToString();
            Type controllerType = filterContext.Controller.GetType();
            var method = controllerType.GetMethod(actionName);
            var returnType = method.ReturnType;

            // If the action that generated the exception returns JSON
            if (returnType.Equals(typeof(JsonResult)))
            {
                filterContext.Result = new JsonResult()
                {
                    Data = "DATA not returned"
                };
            }

            // If the action that generated the exception returns a view
            if (returnType.Equals(typeof(ActionResult))
                || (returnType).IsSubclassOf(typeof(ActionResult)))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Error"
                };
            }
        }

        // Make sure that we mark the exception as handled
        filterContext.ExceptionHandled = true;
    }
}

Declare the model at the top of the error view:

@model System.Web.Mvc.HandleErrorInfo

Then use on the page:

@if (Model != null)
{
    <div>
        @Model.Exception.Message
        <br />
        @Model.ControllerName
    </div>
}

, .

+8

Source: https://habr.com/ru/post/1598128/


All Articles