Pages

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

2 comments:

  1. Excellent - Taught me to put a wrapper around all my ApexPages.xxx usage so I can invoke VF action methods and constructors from execute anonymous

    ReplyDelete