Turi
Turi

Reputation: 171

Redirect to controller action when any error occurs in ASP.NET MVC 5

I need to redirect to a page when any error occurs.

web.config

<customErrors mode="On" defaultRedirect="~/Error/Index">
</customErrors>

ErrorController.cs:

public class ErrorController : BaseController
{
    // GET: Error
    public ActionResult Index(string aspxerrorpath)
    {
        SendMail("Error Web", string.Format("Usuario: {0} .Error en: {1}", UserLogged == null ? "" : UserLogged.FullName(), aspxerrorpath));
        return View("StringData","Se ha producido un error. Intentalo pasado unos minutos o envia un aviso al administrador desde el apartado de sugerencias");
    }
}

enter image description here

Upvotes: 0

Views: 1513

Answers (1)

Anton Norka
Anton Norka

Reputation: 2312

Simple way to add following in Global.asax.cs:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    // Log the exception.
    logger.Error(exception);
    Response.Clear();
    Context.Response.Redirect("~/"); // it will redirect to just main page of your site. Replace this line to redirect whatever you need.
}

Good approach for this is in addition cast exception to HttpException and then process that exception according like that:

HttpException httpException = exception as HttpException;
if (httpException == null)
{
  // should redirect to common error page
}
else //It's an Http Exception, Let's handle it.
{
    switch (httpException.GetHttpCode())
    {
      case 404:
        // Page not found.
        // redirect to another error page if need
        break;
      case 500:
        // Server error.
        // redirect to another error page if need
        break;
      default: // covers all other http errors
        // redirect to another error page if need
        break;
    }
}

Upvotes: 1

Related Questions