Visualforce is Salesforce’s MVC style pages. In this blog post, we’ll cover how to display error messages in a Visualforce page and how to add error messages.
Why Show Error messages
Showing error messages is a really import part of the user experience. A good error message should tell the user exactly what the problem is and how to potentially resolve it. For example, a missing Account Name error should say something like:
“The Account Name is required, please enter one.”
“Account Name is null.”
Displaying Error Messages In the Visualforce Pages
To display messages from the controller or an extension, we need to use the apex:pageMessage or apex:pageMessages visualforce tage. Like so:
An error message being displayed would look something like this in a Visualforce page.
Setting Custom Error Messages in Apex
We can add five different types of error messages to a Visualforce page ranging from Info to Fatal. It’s a really good practice to show custom error messages instead of allowing the page to just error when there’s a problem.
We can add add a custom error to our Visualforce page by using “ApexPages.addMessage()” which accepts a ApexPages.message object. To instantiate a ApexPages.message object we need to pass in an severity ENUM and a message.
Wrapping It up
In this blog article, we went over why and how to show error messages in Visualforce. We also briefly covered how to show custom errors in Apex too!
Also published on Medium.