Question

I´m trying to redirect to an action from one controller to another if something in a try-block goes wrong. What I want to achieve is a general way of presenting a view to the user if something goes wrong in different controllers by directing all errors to an errorhandling ActionResult in my Homecontroller. This is basically what the code looks like:

    try
    {
        Code that may go wrong
    }
    catch (Exception e)
    {
        set the errorcode (integer)

        Logg the error (write a simple textfile)

        RedirectToAction("ErrorHandling", "Home", errorcode);
    }

And in the Homecontroller i would like to generate a view, telling the user that something went wrong:

    public ActionResult ErrorHandling(int errorcode)
    {
        do something with the errorcode

        return View(different view depending on errorcode);
    }

My problem is that if i manipulate the code so that an exception is thrown every step in the catcblock is executed except for the RedirectToAction whic is being ignored. What am i missing? I´m kind of new to this, so hopefully there is a simple answer that i haven´t been able to find...

Was it helpful?

Solution

In your catch block try

  return new RedirectToRouteResult(new RouteValueDictionary
    { 
        {"Controller", "Home"}, 
        {"Action", "ErrorHandling"},
        {"errorcode", errorcode}
    });

Maybe you simply forgot the return in your code:

return RedirectToAction("ErrorHandling", "Home", errorcode);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top