Today I had a very unusual experience while working on a VF page. It's a very simple page and controller but the results were quite strange. Actually, I am trying to save an Opportunity and if there is any exception, I am displaying the message on VF page.

I was using this piece of code --> It was not displaying the page message as it was entering the try block despite hitting a validation rule.

pageref = controller.view();            
system.debug('inside try '+pageref );
Catch(Exception e){
system.debug('inside catch '+e);
pageref = null;

As soon as I replaced controller.save() by upsert, everything became fine. Error messages started to come on the VF page and I could also see the code getting inside catch block.

Can someone explain why such behavior?


I checked everything carefully. When using standardcontroller save, Error is captured inside this method and hence catch block is never executed. It's better to do this if using standardcontroller:

Pagereference pageref = null;
pageref = controller.save();
if(pageref == null)
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'ERROR : Please contact the System Admin.'));

In case of upsert, the error can be easily captured in a catch block. I would also advise not to use:

pageref = controller.view(); 

The url returned from save() method would be enough to handle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.