c#/ asp.net - 如何捕获"System.Web.HttpException:Request timed out"?

ome*_*ega 2 c# asp.net httprequest itextsharp

在我的asp.net/c#项目中,我使用iTextsharp dll从许多pdf文档中读取文本,但有时我会收到此错误

System.Web.HttpException:请求超时.

但是这样做的代码是:

    public static bool does_pdf_have_keyword(string keyword, string pdf_src) 
    {
        try
        {
            PdfReader pdfReader = new PdfReader(pdf_src);
            string currentText;
            int count = pdfReader.NumberOfPages;
            for (int page = 1; page <= count; page++)
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
                if (currentText.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) != -1) return true;
            }
            pdfReader.Close();
            return false;
        }
        catch
        {
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

那么为什么页面在try catch中遇到未处理的异常并且catch应该捕获所有内容?

Ric*_*kir 5

我认为您try没有捕获此异常的原因是您获得的异常不会从您的代码本身抛出,而是从服务器抛出.

以这种方式思考:

  • 你的代码运行正常,只需要很长时间.
  • 服务器监视请求的持续时间,终止请求并抛出异常.

所以你的代码实际上并没有抛出异常.

现在,如果您想了解它或记录它,您可以Application_ErrorGlobal.asax文件中使用该方法(假设您可以访问它,我不确定它如何与SharePoint一起使用).

例如,在我的一个Web项目中,我想记录所有错误,甚至是未捕获的错误.所以我做的是这样的:

protected void Application_Error(object sender, EventArgs e) {
    //Log ALL uncaught exceptions
    Exception exc = Server.GetLastError();
    if (exc is HttpUnhandledException) {
        exc = Context.Error.InnerException;
    }
    //Log error here
}
Run Code Online (Sandbox Code Playgroud)

除了记录它之外,我不确定你能用它做多少.我不知道在页面生命周期中发生了什么,所以我不确定你是否可以做一些事情,比如获取当前的HTTP请求对象并重定向用户.

希望这可以帮助.