Son*_*ner 0 c# asp.net-mvc exception
的Global.asax.cs:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();    
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    GlobalFilters.Filters.Add(new HandleErrorAttribute()); // i added this 
}
protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Response.Clear();
    HttpException httpException = exception as HttpException;
    if (httpException != null
    {
        string action;
        switch (httpException.GetHttpCode())
        {
            case 404:
                // page not found 
                action = "HttpError404";                    
                break;
            case 500:
                // server error
                action = "HttpError500";
                break;
            default:
                action = "General";
                break;
        }
    }
    // clear error on server
    Server.ClearError();
    //return new EmptyResult();
}
行动:
public ActionResult Index()
{
    var a = Convert.ToInt64(""); // I get exception after that project is not running
    return view();
}
题:
我正在尝试在asp.net MVC中使用动态异常.为了做到这一点,我添加了一个方法global.asax.cs.异常处理有效,但是在发生异常后项目不会运行.
当我得到异常时,我希望项目继续运行,就像使用try-catch语句一样,但是当我得到异常时,项目就会停止工作.
要添加什么或要更改什么才能让项目继续运行?
摘要:
Application_Error不处理代码抛出的类型的异常,即使它没有返回任何内容.
详情:
您正在尝试在ASP.NET MVC中使用异常处理的两个不同方面.
如果您HandlerErrorAttribute在GlobalFilters中注册,那么您要说的是,对于任何未被捕获的错误,您要重定向到应用程序的错误页面,默认情况下将在该页面中找到/Views/SharedFolder.
但这只适用于web.config中的customErrors ="On":
<system.web>
    <customErrors mode="On" />
</system.web>
请注意,您也可以HandlerErrorAttribute在Controller或ActionMethod级别而不是全局级别应用.
如果customErrors ="On" 但你没有定义一个Error页面,/Views/SharedFolder那么它将抛出一个类型的复合错误,System.InvalidOperationException而这个错误反过来会冒泡到Application_Error.
另一方面,如果customErrors ="Off",那么HandleErrorAttribute机制将不会触发,而是由Index ActionMethod触发的异常将冒泡到您在Application_Error中定义的GlobalError处理程序.
在这种情况下,异常将与您的代码相关:
var a = Convert.ToInt64("");
这将抛出类型的异常System.InvalidFormatException.
因此,如果您在Application_Error中设置断点,您将看到此方法确实运行但它实际上不会执行任何操作,因为您的switch语句仅假设httpException:
 HttpException httpException = exception as HttpException;
 if (httpException != null)
在这些情况下,httpException将始终为null,因为它们都不是System.InvalidOperationException或System.InvalidFormatException继承自HttpException.
所以你需要做更多的事情:
HttpException httpException = exception as HttpException;
if (httpException == null)
{
  // General exception handling logic here
}
else            
{
  // Http exception handling switch statement here            
}
即使您正确地捕获并处理错误,您也不会使用它或之后执行任何操作:
//return new EmptyResult();
所以你仍然会得到一个空白页面.你应该做一个重定向或Server.Transfer的或东西在这一点上.
| 归档时间: | 
 | 
| 查看次数: | 1305 次 | 
| 最近记录: |