How to Show error messages in Visualforce

Sharing is Caring

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.”

Instead of:

“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.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.