问题
In my asp.net/c# project I am using the iTextsharp dll to read the text from many pdf documents, but sometimes I get this error
System.Web.HttpException: Request timed out.
But the code that does it is:
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;
}
}
So why does the page go into an unhandled exception when it's in a try catch and the catch is supposed to catch everything?
回答1:
I think the reason your try
is not catching this exception is that the exception you're getting is not thrown from your code per se, but from the server.
Think about it this way:
- Your code is running fine, it's just taking a long time.
- The server monitors how long the request is taking, kills the request and throws an exception.
So your code doesn't actually throw that exception.
Now, if you want to find out about it or log it, you can use the Application_Error
method in your Global.asax
file (assuming you have access to it, I'm not sure how that works with SharePoint).
For example, in one of my web projects, I wanted to log all errors, even ones that weren't caught. So what I do is something like this:
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
}
I'm not sure there's much you can do with it other than log it. I don't know where in the page life cycle this occurs so I'm not sure if you could do something like get the current HTTP request object and redirect the user.
Hope this helps.
回答2:
You are catching the exception, but, because it's a ThreadAbortException, the framework is automatically re-throwing it. See here for more information.
The issue is that your PDF keyword searching code is (sometimes) taking longer than the specified HTTP execution timeout. I don't know what the default timeout is for Sharepoint, but you should be able to increase it.
来源:https://stackoverflow.com/questions/13768850/c-asp-net-how-to-catch-system-web-httpexception-request-timed-out