[SalesForce] Clear Apex:PageMessages without losing viewstate

Is there a way to clear the PageMessages in my controller without losing my Page's viewstate?

At the moment I'm doing a ajax call from my visualforce page, which rerenders part of my page, but this could also generate new error messages, I would like to clear older error messages without having to reload my entire page and loose the viewstate.

I've tried

ApexPages.getMessages().clear();

In my extension, without luck, and the documentation doesn't seem to be very helpful on this point either.

Best Answer

There are some alternative ways to display error messages, but like @Mark Pond answered you cannot clear the ApexPages.getMessages(). Also, you cannot iterate over it and replace the elements on it, or rather you can but it doesn't stick just like you observed with the clear() call.

I suspect that the List that is returned by getMessages() is defensive copy of what is actually stored.

There are alternatives, such as doing away completely with apex:pageMessages in favor of using apex:pageMessage and building up your own error message(s) to display under that tag. Obviously there are drawbacks such as maintainability with having to manually handle and report on all of the errors.