2010-02-23 72 views
1

在web.config中:如何使用customErrors捕获异常?

<customErrors mode="RemoteOnly" defaultRedirect="~/Errors.aspx"> 
    <error statusCode="404" redirect="~/Error.aspx?code=404"/>  
</customErrors> 

在后面页面的代码:

throw new HttpException(404, "404 Not Found"); 

在此行中,用一个错误的Visual Studio游:

System.Web.HttpException was unhandled by user code

我应该在哪里赶上这个错误?

回答

2

如果Visual Studio IDE打破了throw线,那么您正在调试模式下运行。在调试模式下,异常会导致执行停止。

尝试运行网站(CTRL + F5)而不是调试网站(F5)。但是,请注意,随后您将获得常规的黄色ASP.NET异常页面,因为您的customErrors标记指定了“RemoteOnly”,这意味着自定义页面将仅显示给远程请求。您的请求不是远程的,因为您在提供页面的计算机上。

要看到的customErrors行动,改变标签:

<customErrors mode="On" defaultRedirect="~/Errors.aspx"> 
    <error statusCode="404" redirect="~/Error.aspx?code=404"/>  
</customErrors> 

,并使用CTRL + F5运行您的网站。

+0

这个,不错。我接受这个答案之前的另一个问题是:是否可以将字符串参数“404 Not Found”传递给重定向页面? – mariki 2010-02-23 17:06:27

+0

不容易。如果这是您的要求,我会绕过customErrors并在global.asax中的Application_Error中编写我自己的异常处理程序。 – 2010-02-23 17:31:51

+0

如果我使用Application_Error,我应该禁用customErrors? – mariki 2010-02-23 17:49:09