I am trying to catch an exception and have it send an email as well as post message back on the case record, when user hit save, so the user will see it as well.

what I am get is this "System.FinalException: ApexPages.addMessage can only be called from a Visualforce page:"

        integer = 10/0;
    } catch (Exception e) {
             // send email code

            // post message on page.
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));          
  • Is this code part of a controller class?
    – Jagular
    Dec 10 '14 at 15:55
  • this code is in a handler class, which is called by a trigger.
    – MCHam
    Dec 10 '14 at 16:22

As the error states the ApexPages methods are only valid when called from a controller associated with a visual force page currently being viewed/accessed.

If you are trying to add an error to a record use:

{THERECORD}.addError('There was an error');

NOTE: This will cause all DML to be rolled back OR DML for the current record to be rolled back depending on the settings of the calling method.

Emails should still be sent out but any DML will not. - Per sfdcfox this will NOT happen, emails will be rolled back.

  • 2
    Actually, any queued emails would also be rolled back, so they won't be sent. Only records that survive all the way to the end of the transaction will send emails.
    – sfdcfox
    Dec 10 '14 at 16:24
  • 1
    It doesn't necessarily mean all DML will be rolled back. It depends on how you do the DML since there are Database methods that allow for successful records to not be rolled back with it.
    – dphil
    Dec 10 '14 at 16:33
  • All this is happening in conjunction with a before trigger, so I am not using any DML statements.
    – MCHam
    Dec 10 '14 at 16:40
  • @dphil - Hence my statement "depending on the settings of the calling method. Although I could make it clearer I was going for succinct
    – Eric
    Dec 10 '14 at 16:52
  • 1
    @MCHam Yes, addError causes a complete rollback of anything that the part of the transaction would have done, including future methods, queueable methods, batch methods, sending emails, and anything else you can think of that would otherwise survive the transaction.
    – sfdcfox
    Dec 10 '14 at 17:31

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.