2016-11-20 89 views
0

我正在嘗試創建Azure工作者角色以下載電子郵件並將它們存儲在數據庫中。當我無法連接郵件服務器或使用郵件服務器進行身份驗證時,我會拋出一些例外情況,但捕獲這些郵件不起作用。無法捕獲Azure工作者角色中的異常

我拋出的異常沒有被try catch塊捕獲。這是爲什麼?我的輔助角色

的RunAsync方法:

private async Task RunAsync(CancellationToken cancellationToken) 
    { 
     // TODO: Replace the following with your own logic. 
     while (!cancellationToken.IsCancellationRequested) 
     { 
      Trace.TraceInformation("Working"); 

      var emailManager = new EmailManager(); 
      var emails = new List<Email>(); 

      try 
      { 
       emails = emailManager.GetNewEmails("outlook.office365.com", 993, "email", "password"); 
      } 
      catch(Exception ex) 
      { 
       Trace.TraceInformation("Error"); 
      } 

      await Task.Delay(1000); 
     } 
    } 

EmailManager.GetNewEmails()

public List<Email> GetNewEmails(string server, ushort port, string username, string password) 
    { 
     var imapClient = new ImapClient(server, port, username, password, false); 
     if (!imapClient.Connect()) 
      throw new Exception("Unable to connect to server."); 
     if (!imapClient.Authenticate()) 
      throw new Exception("Unable to authenticate with server."); 

     var messages = imapClient.GetMessages(); 
     var emails = Mapper.Map<List<MailMessage>, List<Email>>(messages); 

     return emails; 
    } 
+0

你確定你的'EmailManager()'構造函數沒有拋出異常嗎? –

+0

將while循環放入try catch中。這將確保其他語句不會拋出異常。 –

+0

@BrendanGreen我已經在GetNewEmails()內部創建了斷點,並通過逐步遍歷我到達imapClient.Connect()的代碼,然後停止。這是因爲這是我拋出異常的地方,它最終沒有被我的RunAsync方法中的catch塊捕獲。我試圖弄清楚爲什麼它沒有被捕獲到。 – Maritim

回答

0

事實證明該線程實際上沒有崩潰,而是無限期地掛起。這似乎是我使用的電子郵件庫中的一個錯誤,OpaqueMail,當您嘗試建立非SSL POP3或IMAP連接時發生。我在他們的GitHub頁面上向開發者提出了一個錯誤。

當我強制SSL連接時,一切都按預期工作,拋出的異常被捕獲,因爲它們應該是。

所以總結起來,一個錯誤導致線程掛起,問題從未涉及到Azure,異步方法或異常處理。這是一個不透明的郵件錯誤。

相關問題