Error Handling

The two main concerns when handling errors in Visualforce are how uncaught exceptions impact the user interface and how to communicate caught exceptions to users.

Uncaught Exceptions

Allowing an uncaught exception in a trigger is often an appropriate way to notify the user of a problem because Force.com displays a nicely formatted error message to the user in the native user interface. But in a Visualforce page, uncaught exceptions result in an alarming, generic Force.com error page whose appearance cannot be controlled or customized in any way.

As this is typically not consistent with the usability and look and feel of a custom user interface, one of the goals of error handling in Visualforce is to avoid these uncaught exceptions. Place a try, catch block around every action method, or at least those that perform SOSL, SOQL, or DML operations.

A benefit of uncaught exceptions in triggers is that they roll back the current transaction. Catching all exceptions in your Visualforce controller forces your code to roll back explicitly if required by your application. For example, if your controller has two DML statements in an action method and fails on the second with a caught exception, the first statement is still committed to the database at the conclusion of the method. If this leaves the database in an undesirable state for your application, set a savepoint at the beginning of the method and roll back to it in the catch block. For an example of using savepoints, refer to Listing 5.19 in Chapter 5, “Advanced Business Logic.”

Error Communication

Visualforce provides page components and corresponding data objects for communicating errors to the user in a consistent way. The page components are messages and pageMessages, which display the page-level errors returned by a controller. These components are placed on pages, typically at the top, and render the ApexPages.Message objects added to the page. Message objects contain a message and optional severity. Severity is used to style the message when displayed in the pageMessages component and can also be filtered on in test methods.

Listing 6.18 is an example of code to add an error-severity message to the page. To be visible, it must be rendered by a messages or pageMessages component.

Listing 6.18 Sample Usage of Page Messages


ApexPages.addMessage(new ApexPages.Message(
  ApexPages.Severity.ERROR, 'Something went wrong'));


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.100.62