2013-06-05 239 views
2

我們使用Delphi 7運行的軟件通過電子郵件生成併發送報告給各個利益相關者。在每天傳輸的大約30-40個報告中,每天2-4個不同的報告因爲例外而失敗:「EIdConnClosedGracefully」疑難解答EIdConnClosedGracefully異常?

我試圖追蹤爲什麼會發生這種情況,以及如何在代碼中捕獲此信息。下面是我們到目前爲止有:

try 
    // Code that Populates "mess" (a tIdMessage variable) 

    if (not nSMTP.Connected) then 
    begin 
    nSMTP.Connect; 
    end; 

    try 
    nSMTP.Send(mess);  
    except on E : Exception do 
    begin 
     resend := E.Message; 
     // AutoReports_ExceptionMessage is a string that holds the Exception message 
     AutoReports_ExceptionMessage := 'Attempt #1: ' + resend; 
    end; 
    end; 

    if (resend <> '') then // If there is an exception triggered, resend the email 
    begin 
    try 
     nSMTP.Send(mess); 
    except on E : Exception do 
     begin 
     resend := E.Message; 
     AutoReports_ExceptionMessage := 'Attempt #2: ' + resend; 
     end; 
    end; 
    end 

finally 
    mess.Free; 
end; 

此外,當,EIdConnClosedGracefully是觸發時,它總是顯示「嘗試#2:連接關閉擺好。」並從來沒有「嘗試#1:連接關閉優雅地」

任何建議?

+0

這是一個正常的異常...黑體書寫的源代碼。你必須忽略它。 –

回答

4

EIdConnClosedGracefully表示另一方(本例中爲SMTP服務器)已斷開連接的結束。一旦發生異常,您無法將更多數據發送給對方。您必須先重新連接。因此,在您展示的代碼中,如果嘗試#1由於套接字斷開而失敗,則嘗試#2將始終失敗。

試試這個:

for Attempt := 1 to 2 do 
begin 
    try 
    //... 
    if (not nSMTP.Connected) then 
     nSMTP.Connect; 
    nSMTP.Send(mess); 
    AutoReports_ExceptionMessage := ''; 
    Break; 
    except 
    on E : Exception do 
    begin 
     AutoReports_ExceptionMessage := E.Message; 
     nSMTP.Disconnect; 
    end; 
    end; 
end; 

或者:

try 
    // ... 

    if (not nSMTP.Connected) then 
    nSMTP.Connect; 

    try 
    nSMTP.Send(mess);  
    AutoReports_ExceptionMessage := ''; 
    except 
    on E : Exception do 
    begin 
     AutoReports_ExceptionMessage := E.Message; 
     nSMTP.Disconnect;  
     try 
     nSMTP.Connect;  
     nSMTP.Send(mess); 
     AutoReports_ExceptionMessage := ''; 
     except 
     on E : Exception do 
     begin 
      AutoReports_ExceptionMessage := E.Message; 
      nSMTP.Disconnect;  
     end; 
     end; 
    end; 
    end; 
end; 
+0

謝謝@Remy!我實現了第一部分,沒有'如果nSMTP.IOHandler <> nil然後nSMTP.IOHandler.InputBuffer.Clear;'並且會在每天運行一夜之後完成報告。 (我得到InputBuffer未定義,我想也許這是在Delphi 7實施後引入的;或者我不包括必要的東西) –

+0

如果InputBuffer沒有定義,那麼你必須使用Indy 9我給你的是Indy 10。在Indy 10中,如果分配了'IOHandler'並且其'InputBuffer'不爲空,'Connect()'將引發異常。 Indy 9的情況並非如此。 –

+0

非常感謝你@Remy!代碼的第一部分起作用了,並且自從我開始跟蹤這些錯誤以來第一次(可能大約三天,儘管我們已經丟失了**個月**的報告),所有這些錯誤都已發送!非常感激! –