Thursday, March 8, 2012

Salesforce FinalException: "ApexPages.addMessage can only be called from a Visualforce page" in anonymous Apex

When doing some testing using anonymous apex I encountered the following exception:

System.FinalException: ApexPages.addMessage can only be called from a Visualforce page

The solution was to check if there was a current page before attempting to add the message:

if(ApexPages.currentPage() != null){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                                'Some very important message for the user'));
}