Are DML changes rolled back when an exception occurs in Visualforce?
It is clear from the official Salesforce documentation that all database modifications initiated from a trigger are rolled back when an exception occurs. We can look at it as if the application server started a transaction in our behalf, and handled the roll back if an exception is thrown and is not handled.
But, what happens with exceptions in VisualForce?
From reading some of the documentation, it may not be as clear how the application behaves when an exception occurs as a result of a VisualForce interaction. Are DML changes rolled back when an exception occurs as a consequence of a VisualForce request? Well, it turns out it’s pretty easy to test it, so I went ahead and did that.
I used just two components for my test:
- A VisualForce page
- A Controller for our VisualForce page
This is the code for the VisualForce page:
This is the code for the Controller:
The only thing that the VF page does is call the throwException method when the user clicks on the “Click Me” button.
In the throwException method the second insert fails because the name field is required when creating a pricebook.
If you look at the database state after clicking the button, you will see that neither insert went through. (You can comment out the second one to make sure the first one works.)
So from our test it is clear that VisualForce pages display the same behaviour triggers do, and that all database changes are rolled back when an exception occurs.
This behavior is consistent with the way exceptions are handled everywhere else, and we could imagine that internally Salesforce is using something like Java filters for establishing transaction boundaries, in a fashion similar to how it’s done in the Spring framework.