对EIdConnClosedGracefully例外进行故障排除?

时间:2013-06-05 16:05:11

标签: delphi exception-handling delphi-7

我们使用Delphi 7运行的软件通过电子邮件生成报告给各利益相关方。在每天发送的大约30-40份报告中,每天有2-4份不同的报告因例外情况而失败:“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:连接正常关闭”

有什么建议吗?

1 个答案:

答案 0 :(得分:6)

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;
相关问题