【发布时间】:2010-12-26 10:39:12
【问题描述】:
如果我有 pageUrl,如何获得编译器错误消息?
我尝试使用 HttpWebRequest 类,但还没有得到结果。
我有页面集合,必须自动执行,如果页面失败,我需要它来创建日志。
谢谢
【问题讨论】:
-
您在哪里尝试捕获和记录这些错误?页面失败时在服务器上,还是在访问页面并提供错误服务的外部应用程序中?
标签: c# asp.net .net-3.5 logging
如果我有 pageUrl,如何获得编译器错误消息?
我尝试使用 HttpWebRequest 类,但还没有得到结果。
我有页面集合,必须自动执行,如果页面失败,我需要它来创建日志。
谢谢
【问题讨论】:
标签: c# asp.net .net-3.5 logging
您可以在 Application_Error 处理程序的应用程序全局类 (global.asax) 中捕获所有应用程序错误。
其他方式。您也可以在自定义错误模块中捕获异常,只需在 <httpModules> 部分注册您的模块并在那里实现以下功能:
void context_Error(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
Exception ex = context.Server.GetLastError();
//... here goes some code
}
因此,您必须设法捕获任何错误。其他任务是请求所有页面。从您的帖子中我可以看出,您已经有了这样的解决方案。
【讨论】:
string pagetext = (new System.Net.WebClient()).DownLoadString(<url>);
//Add a better control here
if(pagetext.Contains("Server Error"))
{
`enter code here`
}
【讨论】:
<customErrors mode="RemoteOnly" defaultRedirect="/errorPage.aspx"。这是默认设置,但如果您将模式设置为“开”,您将无法从页面读取错误,或者如果您将其设置为“关”,您会将错误消息暴露给网络(这将是坏的。)
如果请求的响应是 HTTP 错误,您可以编写一个程序来访问这些页面,而您可以进一步调查。
如果您不想编写自己的程序来检测源自 HTTP 请求的错误,您可以使用像 selenium 这样的测试框架。
【讨论】:
免责声明:我很少使用 ASP.NET 类型的东西。
ELMAH 可能会对您有所帮助。它是 ASP.NET 项目的错误记录器。
【讨论】:
您在哪里尝试捕获这些异常?在您的网站中,还是在抓取网站的外部应用程序中?
在外部应用程序中,使用 HttpWebRequest 可以执行以下操作:
string urlToTry = "http://www.example.com/ServerErrorPage.htm";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToTry);
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Process your success response.
}
catch (WebException we)
{
HttpWebResponse error = (HttpWebResponse)we.Response;
// If you want to log multiple codes, prefer a switch statement.
if (error.StatusCode == HttpStatusCode.InternalServerError)
{
// This is your 500 internal server error, perform logging.
}
}
WebException 类会给你这样的消息:
远程服务器返回错误:(500) Internal Server Error.
将它们转换为 HttpWebResponse 后,您可以访问 StatusCode 并执行您需要的任何日志记录。
【讨论】: