将基本异常转换为HttpException

时间:2017-08-10 13:35:35

标签: c# asp.net exception

我正在开发ASP.Net应用程序,而我目前正在努力处理异常处理问题。我已经设法进行了适当的异常处理,但我真的不知道如何处理不适合用户界面的内部错误。

void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    LogManager.GetCurrentClassLogger().Error(ex);
    Response.Clear();

    HttpException httpEx = ex as HttpException;
    if (httpEx == null)
    {
        switch(ex.GetType())
        {
            //Convert ex into httpexception 
            //with statuscode that depends on the exception type
        }
    }

    RouteData routeData = new RouteData();
    routeData.Values.Add("controller", "Error");
    routeData.Values.Add("action", "Handler");
    routeData.Values.Add("exception", httpEx);
    Server.ClearError();
    Response.TrySkipIisCustomErrors = true;

    var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
    var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Error");
    c.Execute(rc);
}

1 个答案:

答案 0 :(得分:2)

而不是尝试将您的例外转换为HttpException,而只是尝试创建一个新的HttpException,将原始例外作为内部例外:

HttpException httpEx = new HttpException(500, msg, ex);