Last week at the Paris World Tour I was asked a question about the getContent() and getContentAsPDF() methods on the PageReference class. I was rushed and gave the best answer that I could at the time. However, as the two gentlemen left me I had a nagging feeling that I was missing a piece of information. This morning I have finally found the time to come back to the question and get the complete answer. But first the question;

Why do getContent() and getContentAsPDF() throw an exception when called from a future method, despite the documentation saying that you can do this?I have to admit I was surprised by this question but the guys demonstrated their code to me and sure enough it blew up. The code was in the depths of a custom app that they had built but it can be boiled down to the following;

I was told that the breaking change that had been made was when they made Method2 a @future method. The documentation for getContent() says that it can’t be executed from a series of different types asynchronous apex but it doesn’t mention future methods. Hence I expected their code to work… that or the documentation had a flaw in it.

So, with a syncing feeling in my heart this morning I signed up for a perfectly clean new developer org, opened up the dev console, created TestClass1 and called Method1 from the Execute Annoymous window. It behaved exactly as I would have expected: the blob was generated and no exceptions were thrown.

At this point, had I not seen the issue in Paris first hand I would have just walked away. But I had seen the error myself and so wasn’t going to give up that easily – there must have been some difference in our setup. I dug through the depths of my brain and the remembered that Summer ’15 introduced this Critical Update: getContent() Method Behave as Callouts. I hadn’t checked the org last week for this but it seemed like it would cause an exception; time to activate the critical update and test again.

This time when executing the same code I got this in the debug log;

Screenshot 2015-06-30 08.48.49

And there we have it! Not only that the exception message even tells you how to fix it!

I have to admit I feel a bit sheepish writing this post and for a multitude of reasons; I should have remembered about the critical update on the day, I should have checked the debug log, I should have just given the guys in Paris a better answer. So hopefully this will get to them somehow and atone for my sins.

However, the other message I would like to spread is: Please, everyone, check your debug logs when you see an exception. In this particular case checking the log and seeing the exception would have led to a quick fix. It might not have completely explain the situation away but it would have fixed the “urgent” problem that was facing them in a production environment.