I am creating some records in my controller but some of them might fail during insert due to duplication, so I use Database.insert(records, false).

It works just fine and ignores records that already exist. But when I use <apex:pageMessages /> in my page, it tells me:

Error: Error while inserting/updating My SObject: Duplicate Entry!

So apex skips the errors, but they are still existing in the execution context, so they are displayed in VF. Any Idea how to keep the insert(x, false) but also use pageMessages? I'm trying to avoid an extra query doublechecking duplicated records.

2 Answers 2


It is not possible to modify the ApexPages.getMessages() collection so you have no choice but to avoid using apex:pageMessages.

Instead of apex:pageMessages you could use apex:pageMessage and supply your own filtered messages from your controller:

public class YourController {

    public class Message {
        public String summary {get; set;}
        public String severity {get; set;}
        Message(String summary, String severity) {
            this.summary = summary;
            this.severity = severity;

    public Message[] getMessages() {
        Message[] messages = new Message[] {};
        for (ApexPages.Message am : ApexPages.getMessages()) {
            if (!am.getSummary().contains('Duplicate Entry')) {
                messages.add(new Message(
        return messages;


displaying them like this:

<apex:repeat value="{! messages }" var="m">
    <apex:pageMessage summary="{! m.summary }" severity="{! m.severity }"/>

(Haven't tested this code but have something similar in an Angular app.)


Use rendered attribute of apex:pageMessages

<apex:pageMessages rendered="{!if(contains(ERROR MESSAGE,'Duplicate entry'),'false','true')}"/>

You can also create a Boolean variable in controller and make it true/false based on error message in code.

  • 2
    This will hide any other error messages any time there is a "Duplicate entry" error which is bad. Also don't see how you can check the error message content without doing the work in the controller.
    – Keith C
    May 2, 2017 at 13:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .