0

I have stitched together an error handling for my application using a solution in this post Link. The problem I am getting is that the app is still routing to the default error page. The code goes all the way to the Global.asax when I breakpoint it, but when the view custom error page should load it loads the default error page from the solution. I tried to remove the default error page, I then got the yellow error page from IIS. Searched the web tirelessly, But to no result. Grateful for all the help. If you think I can tweak the question or Title better, I am open to suggestions.

Error controller:

public class ErrorController : Controller
{
    public ActionResult PageNotFound(Exception ex)
    {
        Response.StatusCode = 404;
        return View("Error", ex);
    }

    public ActionResult ServerError(Exception ex)
    {
        Response.StatusCode = 500;
        return View("Error", ex);
    }

    public ActionResult UnauthorisedRequest(Exception ex)
    {
        Response.StatusCode = 403;
        return View("Error", ex);
    }

    //Any other errors you want to specifically handle here.

    public ActionResult CatchAllUrls()
    {
        //throwing an exception here pushes the error through the Application_Error method for centralised handling/logging
        throw new HttpException(404, "The requested url " + Request.Url.ToString() + " was not found");
    }
}

Code in Global.asax.cs:

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();

        //Error logging omitted

        HttpException httpException = exception as HttpException;
        RouteData routeData = new RouteData();
        IController errorController = new Controllers.ErrorController();
        routeData.Values.Add("controller", "Error");
        routeData.Values.Add("area", "");
        routeData.Values.Add("ex", exception);

        if (httpException != null)
        {
            //this is a basic example of how you can choose to handle your errors based on http status codes.
            switch (httpException.GetHttpCode())
            {
                case 404:
                    Response.Clear();

                    // page not found
                    routeData.Values.Add("action", "PageNotFound");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

                    break;
                case 500:
                    // server error
                    routeData.Values.Add("action", "ServerError");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
                case 403:
                    // server error
                    routeData.Values.Add("action", "UnauthorisedRequest");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
                //add cases for other http errors you want to handle, otherwise HTTP500 will be returned as the default.
                default:
                    // server error
                    routeData.Values.Add("action", "ServerError");

                    Server.ClearError();
                    // Call the controller with the route
                    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
                    break;
            }
        }
        //All other exceptions should result in a 500 error as they are issues with unhandled exceptions in the code
        else
        {
            routeData.Values.Add("action", "ServerError");
            Server.ClearError();
            // Call the controller with the route
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
    }

RouteConfig.cs

  routes.MapRoute("CatchAllUrls", "{*url}", new {controller = "Error", action = "CatchAllUrls"});

The catch block:

throw new HttpException(404, "Unable to write to list" + ", " +  e.InnerException);
gorkem
  • 731
  • 1
  • 10
  • 17
AllramEst
  • 1,319
  • 4
  • 23
  • 47
  • Do you have `` in the `` section of the web.config? – Georg Patscheider Jul 13 '17 at 12:46
  • Is this your ErrorController get's executed? I think you should redirect instead. See [this article](https://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine). – miszczak Jul 13 '17 at 12:49
  • Wich one of the six exaples do you think fits me best? – AllramEst Jul 13 '17 at 12:52
  • @GeorgPatscheider When i add `` to ``. the page goes blank instead of the IIS page. – AllramEst Jul 13 '17 at 12:53
  • The following solution redirects the custom error to the ErrorController without using `Application_Error`: https://stackoverflow.com/questions/13905164/how-to-make-custom-error-pages-work-in-asp-net-mvc-4 Also take a look at this blog concerning common pitfalls: http://benfoster.io/blog/aspnet-mvc-custom-error-pages – Georg Patscheider Jul 13 '17 at 13:22
  • I got it to work and using `Application_Error: `. The view names in Error controller was all wrong. But I cant seem to add status codes to Global.asax. When I add status code 400 in Global.asax and in the controller and a view the code searches for the default error page when it hits 400 in Global.asax. – AllramEst Jul 13 '17 at 13:28
  • I would suggest you to use the method 6 mentioned in the post by @miszczak. This works for me `HttpContext.Current.Server.TransferRequest("/Error/Index");` in the `Application_Error`. – Ali Ashraf Jul 13 '17 at 13:36
  • @AliAshraf Your suggestion worked better. now I can add status codes. But idet get the message that I specified in the throw. Any Ides on how to get it? Got this error message instead `The model item passed into the dictionary is of type 'System.Web.Mvc.HandleErrorInfo', but this dictionary requires a model item of type 'System.Exception'.` – AllramEst Jul 13 '17 at 13:42
  • i use something like following in my base controller's OnException method to add custom error ` filterContext.HttpContext.AddError(new Exception("mycustomerror_code"));` – Ali Ashraf Jul 13 '17 at 14:10
  • Sorry for being a hassle but do you have any example on how to use I. Googled it and found a lot of answers. But couldn't find how to get a message from the catch in my workplanRepo to the onException in the base controller. Is it possible? – AllramEst Jul 13 '17 at 14:30
  • Solved it. I changed this `return View("Error", ex.Message);` to this `return View("Error", ex);` in the controller – AllramEst Jul 13 '17 at 20:04

1 Answers1

0

With the help of @GeorgPatscheider and @AliAshraf I finally solved my issue.I got it to work by changing this return View("Error", ex.Message); to this return View("Error", ex); and added <customErrors mode="On"/>. Now I can also add additional HTTP errorcodes. I had added Message to ex after the initial post Thanks for all the help!!!

AllramEst
  • 1,319
  • 4
  • 23
  • 47