Search code examples
c#asp.net-mvchandleerror

Handling all errors


Good day to all! Trying to solve a problem. I use a method that handles all errors on the site (This method found on the blog of one man)

Global.asax

protected void Application_Error(object sender, EventArgs e)
{
    HttpContext ctx = HttpContext.Current;
    Exception ex = ctx.Server.GetLastError();
    ctx.Response.Clear();

    RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
    IController controller = new CategoryController(); 
    var context = new ControllerContext(rc, (ControllerBase)controller);

    var viewResult = new ViewResult();

    var httpException = ex as HttpException;
    if (httpException != null)
    {
        switch (httpException.GetHttpCode())
        {
            case 404:
                viewResult.ViewName = "Error404";
                break;

            case 500:
                viewResult.ViewName = "Error500";
                break;

            default:
                viewResult.ViewName = "Error";
                break;
        }
    }
    else
    {
        viewResult.ViewName = "Error";
    }

    viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action"));
    viewResult.ExecuteResult(context);
    ctx.Server.ClearError();
}

When I start Projects in the studio, causing the error. I get exception at that code:

RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;

Exception:

Unable to cast object of type 'System.Web.DefaultHttpHandler' to type 'System.Web.Mvc.MvcHandler'

Once I stop debugging (Shift + F5). This method works well and handles any errors. But at the start of project, causing the error. Looking for a solution to these topics, but this problem is not found. Help please.

[HandleError]
public class CategoryController : Controller
{
     // some methods
}

Solution

  • Solved his problem by using code:

    void Application_Error(object sender, EventArgs e)
            {
                Exception ex = Server.GetLastError();
                if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
                {
                    Response.Redirect("~/Error/404");
                }
                else
                {
                    Response.Redirect("~/Error/Other");
                }
                Server.ClearError();
            }