2

In my Web.config I have.

<customErrors mode="On" defaultRedirect="~/Errors/Unknown">
  <error statusCode="403" redirect="~/Errors/Forbidden"></error>
  <error statusCode="404" redirect="~/Errors/NotFound"></error>
</customErrors>

It works fine if I try to open a page that doesn't exist. (It redirects to my custom error page: ErrorsController.NotFound). When an unhandled exception occurs (in this case in LINQ Signle(...)). It doesn't go to ~/Errors/Unknown, but displays default message:

Error. An error occurred while processing your request.

How replace it with my ErrorsController.Unknown ?

Andrzej Gis
  • 13,706
  • 14
  • 86
  • 130
  • http://stackoverflow.com/questions/16312588/in-asp-net-mvc-4-what-is-the-best-show-unhandled-exceptions-in-my-view I believe this question will help to answer yours. – newtonrd Jul 28 '13 at 22:40
  • You might also find this helpful: http://stackoverflow.com/a/13905859/1373170 – Pablo Romeo Jul 28 '13 at 23:00
  • Actually this helped: http://stackoverflow.com/questions/1171035/asp-net-mvc-custom-error-handling-application-error-global-asax – Andrzej Gis Jul 29 '13 at 00:42

1 Answers1

3

Thanks to this question I figured out how to do this. The code below is almost the same as the accepted answer's. The modification handles no HttpExceptions too.

Steps to make it work:

  1. customErrors element in web.config will now be ignored
  2. Paste the method below to your Global.axax.

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        Response.Clear();
    
        var httpException = exception as HttpException;
    
        if (httpException != null)
        {
            string action;
    
            switch (httpException.GetHttpCode())
            {
                case 404:
                    // page not found
                    action = "NotFound";
                    break;
                case 403:
                    // forbidden
                    action = "Forbidden";
                    break;
                case 500:
                    // server error
                    action = "HttpError500";
                    break;
                default:
                    action = "Unknown";
                    break;
            }
    
            // clear error on server
            Server.ClearError();
    
            Response.Redirect(String.Format("~/Errors/{0}", action));
        }else
        {
            // this is my modification, which handles any type of an exception.
            Response.Redirect(String.Format("~/Errors/Unknown")); 
        }
    }
    
Community
  • 1
  • 1
Andrzej Gis
  • 13,706
  • 14
  • 86
  • 130