How to display Error Messages in the Salesforce Visualforce Page?

How to display Error Messages in the Salesforce Visualforce Page?

To display error messages in the Visualforce page add below tag where you want to display the error message.

Visualforce page:

<apex:pageMessages />

Apex Controller:

ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error Message.');
ApexPages.addMessage(myMsg); 

(Or)

ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error Message.'));

Sample Code:

Visualforce Page:

<apex:page controller="SampleVisualforcePageController">
    <apex:pageMessages id="errMsg"/>
    <apex:form>
    	<apex:commandButton value="Show Error Message" action="{!showErrorMsg}" reRender="errMsg"/>
    </apex:form>
</apex:page>

Apex Class:

public class SampleVisualforcePageController {
    
    public void showErrorMsg() {
        
        ApexPages.addMessage( 
            new ApexPages.Message( ApexPages.Severity.ERROR, 'Some Error Occurred' ) 
        );
        
        ApexPages.addMessage( 
            new ApexPages.Message( ApexPages.Severity.INFO, 'Some Info' ) 
        );
        
        ApexPages.addMessage( 
            new ApexPages.Message( ApexPages.Severity.WARNING, 'Some Warning' ) 
        );
        
        ApexPages.addMessage( 
            new ApexPages.Message( ApexPages.Severity.CONFIRM, 'Confirm Message' ) 
        );
        
        ApexPages.addMessage( 
            new ApexPages.Message( ApexPages.Severity.FATAL, 'Fatal Message' ) 
        );
        
    }
    
}

Output:

Leave a Reply