Search code examples
c#.netazureazure-worker-roles

Unable to catch exception in Azure Worker Role


I am attempting to create an Azure Worker Role to download emails and store them in a database. I'm throwing some exceptions when I can't connect or authenticate with a mail server, but catching these is not working.

The exceptions I throw are not being caught by the try catch block. Why is that?

The RunAsync method of my worker role:

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;
    }

Solution

  • As it turns out the thread is not actually crashing, but hanging indefinitely. This appears to be a bug in the e-mail library I'm using, OpaqueMail, which occurs when you attempt to establish a non-SSL POP3 or IMAP connection. I've raised a bug with the developer on their GitHub page.

    When I force an SSL connection everything works as expected and exceptions that are thrown are caught as they should be.

    So to sum it up, a bug caused the thread to hang, the problem was never related to Azure, asynchronous methods or exception handling. It was an OpaqueMail bug all along.