Redirect to error page when entering catch

Asked

Viewed 623 times

4

I have a question as to a possible improvement in the method when an error occurs in a Action and redirect to an error page. At the moment, I do so on Action:

 public ActionResult Index()
    {
        try
        {
            //Um código qualquer aqui 
            return View();
        }
        catch (Exception ex)
        {
            return RedirectToAction("Index", "Erro");
        }
    }

That is, in case of a code error I redirect to the Action Indexof Controller Erro. It turns out, this method I use has a problem. When the View that I will return is inside a Modal, the error page is kind of displayed inside the Modal, getting the layout totally disfigured.

With this, I would like to know if there is a better or more correct way than when throwing an error exception, redirect to the correct page.

  • As you are calling the Modal, could add this part?

1 answer

1

Hello,

This will depend a lot on the rules of your system, but generally the common is to let the error occur in the application so that your server returns a code 500 when some error occurs.

Just as a page not found returns a status code 404, when an error happens internally in your application the request returns a status code 500.

These errors already redirect the client to a default page, but you can customize which pages the client will be redirected to in case of any server error through the web.config of your application by adding these settings:

<customErrors mode="On"  defaultRedirect="~/Error/500">
  <error statusCode="404" redirect="~/Error/404" />
  <error statusCode="500" redirect="~/Error/500" />
</customErrors>

You can add settings for all status codes where redirect is the Action to which the client will be redirected.

The estate defaultRedirect is the Action to which the client will be redirected if the error status code is not specified.

Using this approach your application will generate error logs on your server when something happens, this can be very useful if you need to check something.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.