Convert base Exception into HttpException

倖福魔咒の 提交于 2020-01-06 04:37:49

问题


I'm developing ASP.Net application and I'm currently struggling with exception handling. I've already managed to do proper exception handling but I don't really know how to handle internal errors that are not suitable for UI.

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:


Instead of trying to cast your exception to a HttpException just try to create a new HttpException with the original exception as the inner one:

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


来源:https://stackoverflow.com/questions/45615302/convert-base-exception-into-httpexception

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