2015-11-05 81 views
1

我們有一個圖像上傳頁面,如果用戶的上傳時間超過15分鐘,將會超時。使用HttpException捕獲超時

我們正在捕獲發生超時的HttpException。但是我們怎麼能知道由於超時而發生異常,所以我們可以返回一個特定的消息?

我們的代碼:

try 
{ 
    // do stuff here 
} 
catch (HttpException ex) 
{ 
    // What can we check to know if this is a timeout exception? 
    // if (ex == TimeOutError) 
    // { 
    //  return "Took too long. Please upload a smaller image."; 
    // } 
    return "Error with image. Try again."; 
} 
catch (Exception ex) 
{ 
    return "Error with image. Try again."; 
} 

什麼超時錯誤的樣子:

System.Web.HttpException (0x80004005): Request timed out. 
at System.Web.HttpRequest.GetEntireRawContent() 
at System.Web.HttpRequest.GetMultipartContent() 
at System.Web.HttpRequest.FillInFormCollection() 
at System.Web.HttpRequest.EnsureForm() 
at System.Web.HttpRequest.get_Form() 
at MyStore.upload.ProcessRequest(HttpContext context) 

ex.ErrorCode=-2147467259 
ex.GetHttpCode=500 
ex.WebEventCode=0 

我猶豫簡單地做一個if語句的錯誤代碼進行比較的上方。

HttpCode 500似乎是一個通用的Internal Server Error代碼,可能發生的不僅僅是一個超時異常。

ErrorCode -2147467259是我不熟悉的東西。如果該數字在超時錯誤中保持不變,並且永遠不會發生非超時例外情況,那麼我可以對此數字進行if比較。

我想必須有一個簡單的方法來知道,如果HttpException是超時異常,ALA是這樣的:

if (ex == TimeoutError) // what should this be? 

UPDATE:

我剛纔試圖追趕TimeoutException ,如下所示,但它仍然只能被HttpException捕獲。

try 
{ 
    // do stuff here 
} 
catch (TimeoutException ex) 
{ 
    // Timeout doesn't get caught. Must be a different type of timeout. 
    // So far, timeout is only caught by HttpException. 
    return "Took too long. Please upload a smaller image."; 
} 
catch (HttpException ex) 
{ 
    // What can we check to know if this is a timeout exception? 
    // if (ex == TimeOutError) 
    // { 
    //  return "Took too long. Please upload a smaller image."; 
    // } 
    return "Error with image. Try again."; 
} 
catch (Exception ex) 
{ 
    return "Error with image. Try again."; 
} 
+0

前的typeof TimeoutException異常 –

+0

@YaWang你應該把那作爲一個答案。 –

+0

你去那裏:D –

回答

0

您需要使用

ex.getType() is subClassException 

由於TimeoutException異常是一個子類。這將是如何捕捉這種類型的執行,如果它是一個可能的投擲...

儘管httpexpection將始終拋出,即使它超時(請參閱https://msdn.microsoft.com/en-us/library/system.web.httprequest(v=vs.110).aspx從每個方法拋出)。所以,你需要做這樣的事情,

if(e.Message.Contains("timed out")) 
    //Do something because it timed out 
+0

不編譯。如果這是VB代碼,請用C#回答。當一個問題有一個語言特定的標籤,在這種情況下,'C#',這是他們要求的語言。 –

+0

你的編輯仍然不能編譯。我假設你的意思是'ex.GetType()是TimeoutException'的代碼。注意大寫的'GetType()'和實際的'TimeoutException'。無論如何,即使是固定的代碼也不行。編譯警告:'給定的表達式從不提供('System.TimeoutException')類型'。 –

+0

@DougS我看到你的問題...即使它確實超時,它也不會拋出TimeoutException。它永遠不會總是隻拋出一個HTTP異常,以告訴你需要獲取該消息的消息並執行。包含在字符串消息中 –