9

I have this code in global.asax

 protected void Application_Error(object sender, EventArgs e)
        {
            // ...
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Home");
            routeData.Values.Add("action", "Error");

            IController controller = new Controllers.HomeController();
            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

        }

how can I add parameter to Action method / RouteData ? I would like to show exception message to the user.

Muflix
  • 6,192
  • 17
  • 77
  • 153
  • Why do you want to call the controller method on error, instead call the service or the business logic from Application Error? – Sulay Shah Jan 05 '17 at 06:03
  • do you mean to process error and return a view directly from global.asax ? – Muflix Jan 05 '17 at 08:29
  • what exactly you want to do with application error block, want to log error or make database call to log error? – Sulay Shah Jan 05 '17 at 11:09
  • I am already logging the error to the database in the `Application_Error` but I want to show an error page to the user with the basic description of the error. – Muflix Jan 05 '17 at 16:51

2 Answers2

2

I have figure it out,

routeData.Values.Add("message", exception.Message);

and in action just catch that parameter

public ActionResult Index(string message)
Muflix
  • 6,192
  • 17
  • 77
  • 153
1

To show the custom error page you need to change the web.config.

<system.web> <customErrors mode="On" defaultRedirect="~/Error"> <error redirect="~/Error/NotFound" statusCode="404" /> </customErrors> </system.web>

You can create error pages for different status code.

Make sure you have controller and action method to return view.

After Application_error MVC it self will redirect to the same page as described in web.config.

Please refer this link for more information.

Sulay Shah
  • 524
  • 2
  • 10
  • In this case, how can I access the error exception in the action ? – Muflix Jan 06 '17 at 10:29
  • The exception will be accessed at the Application_error level, the .net will redirect to the action described in the config file. The action should only return view – Sulay Shah Jan 06 '17 at 13:07
  • but how can I display the error description (exception message) in the view ? – Muflix Jan 06 '17 at 13:47