异常不能转换为HttpException

时间:2018-05-18 10:12:03

标签: c# asp.net asp.net-mvc exception-handling

任何人都可以解释当我抛出HttpException时会出现什么原因,当它冒出来时,无法从Exception中获取。 给了一个更多的上下文,我有一个通用的剃刀视图与try..catch的异常,调用子视图,并在子视图中我抛出HttpException。 问题是在通用视图中,Exception无法在引发时被转换为HttpException。 这只发生在一个测试环境中,在我的本地机器中这是有效的(如预期的那样)。

代码:

儿童观点:

...
 }
    else
    {
        throw new HttpException(400,"Not Found");

    }

通用视图

try
{
    @Html.CachedPartial(moduleItem.DocumentTypeAlias, moduleItem, 60 * 60 * 24 * 365,
                                                                           contextualKeyBuilder: (model, viewData) => { return string.Format("{0}|{1}", moduleItem.Id, Request.QueryString); },
                                                                           viewData: ViewData)
}
catch (Exception ex)
{
    //the ex.GetType() is Exception when HttpException is raised 
    if (ex != null && ex.GetType()== typeof(HttpException))
    {
        var httpExp = ex as HttpException;
        var code = httpExp.GetHttpCode();
        if (code == 400)
        {
            HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;
            var xpathQuery = String.Format("//error404");
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            var contentService = umbracoHelper.TypedContentAtXPath(xpathQuery);
            var culture = System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
            var moduleItem404 = contentService.FirstOrDefault(x=> x.GetCulture().TwoLetterISOLanguageName== culture);
            @Html.CachedPartial(moduleItem404.DocumentTypeAlias, moduleItem404, 60 * 60 * 24 * 365,
                                                                           contextualKeyBuilder: (model, viewData) => { return string.Format("{0}|{1}", moduleItem404.Id, Request.QueryString); },
                                           viewData: ViewData)
}
else
{
    throw ex;
}
}
else
{
    throw ex;
}

任何想法,提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用此代码来捕获不同类型的异常

try {
// code
}
catch (HttpException ex){
// code
}
catch (Exception ex){
// code
}