Handling all exceptions within global.asax

*爱你&永不变心* 提交于 2019-12-06 15:58:15

Yes. Here's what I'm doing, but it's not perfect unfortunately.

First, Turn off custom errors.

<customErrors mode="Off" />

Next, Change HttpErrors to Detailed. Note this is the part that I don't particularly like, mainly because if you do this it seems you might be making your stack traces accessible. I think so long as you handle all status codes in your error handling, by using a catch all, you should be OK. Please correct me if I am wrong.

<httpErrors errorMode="Detailed" />

You'll also need a catch all route in your global.asax to catch all MVC routes that don't match your defined routes, and send them to your 404. This could be problematic depending on your route setup, mainly, if you rely on a catch all route to handle your current non-404 routes. I use reflection to define all of my routes based on Action methods in my Controllers, so I don't rely on a catch all pattern for my application's routes.

Lastly, handle the errors in your global.asax. Use a catch all (such as 500) and do special routing for anything you want different, such as 404 errors.

protected void Application_Error(object sender, EventArgs e)
{
    var ex = Server.GetLastError().GetBaseException();

    Server.ClearError();

    var routeData = new RouteData();
    routeData.Values.Add("controller", "Error");
    routeData.Values.Add("action", "500");

    if (ex.GetType() == typeof (HttpException))
    {
        var httpException = (HttpException) ex;
        var code = httpException.GetHttpCode();

        // Is it a 4xx Error
        if (code % 400 < 100)
        {
            routeData.Values["action"] = "404";
        }
    }

    IController errorController = new ErrorController();
    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}

Note, in my example I treat all errors except for 4xx errors as 500. Also, in this example I'm using a controller named "ErrorController" and two actions named "500" and "404".

I hope this helps, and if you find a workaround to to the HttpErrors needing to be set to "Detailed", please do share!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!