Sep 18, 2013

DeleteRestrictedByFkException not found in section Exception


While working on a project recently, our newest addition to the team, Will, stumbled upon an undocumented bug when handling exceptions.

Error: __MISSING LABEL__ PropertyFile - val DeleteRestrictedByFkException not found in section Exception

Scenario:  When deleting a record that is a parent on a restrictedDelete Lookup field, deletion will fail throwing an exception describing the child-records that exist, preventing the deletion.  Normally, passing this exception to an ApexPages.addMessages() for use on a Visualforce page within an <apex:pageMessages />, a VF_PAGE_MESSAGE is encountered and pushed to the page instead of the expected exception (as seen in the screenshot above).

Using a standard dev org, I was able to quickly replicate this, using the sample record data provided. One of the pre-made Accounts ("United Oil & Gas Corp.) was associated with a few different cases.



If you attempt to delete the Accout in the Salesforce.com UI, you'll be directed to a new page that informs youthat it can't be removed due to the Account being related to various Case records (Case.AccountId).



Programatically, you can can do it with the following sample code.


Visualforce Page:


Apex Class:


When you access the new Visualforce page with the Account's ID (https://yourInstance.visual.force.com/apex/errorTest?id=001i000000JEOgk), you'll see:



The "Delete" button is designed to delete the Account record matching the ID in the URL.  We know we enountered an error in the UI, so we know to expect a page message along the lines of "System.DmlException: Delete failed. First exception on row 0 with id 001i000000JEOgkAAH; first error: DELETE_FAILED, Your attempt to delete United Oil & Gas Corp. could not be completed because it is associated with the following cases.: 00001001, 00001002, 00001021, 00001022, ..., ..., ..."

However, we see:



If we look at the debug logs, we can see the exception we wanted occuring ([7] below), but then we see the DeleteRestrictedByFkException VF_PAGE_MESSAGE occuring when the original exception is being passed to apexPages.addMessages(e) [9]:



I opened a Case with Salesforce support to see if there was another issue or if it was indeed a bug:
 "...this is a known issue with salesforce and we have noticed the same in the past which is currently with our R&D department, Unfortunately, we have not recieved any ETA for the fix..."
"We have noticed this error in different conditions and the R&D is working on the same to quickly fix this as soon as possible." 

If you're looking for a solution, I simply replaced:

With: