Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Visualforce Controller Good Example with try/catch
// Record the place "in time" where we would ultimately like to return the state of the database to upon an error.
Savepoint sp = Database.setSavepoint(); // <<<<<<<<<<<<
// New account
Account a = new Account(Name = 'New Account');
try{
insert a;
system.debug('Success');
} catch(dmlexception e){
// If DML failed, ends up here
system.debug('Error inserting account: ' + e);
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Could not insert account record. Error: ' + e));
// Upon error roll back the database
// this example would not do anything since Account is first, and upon failure "a" would not be in the database anyway
Database.rollback(sp); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
// ************ Assume that the account was a success above, continue below ***********
// New Case linked to account
Case c = new Case(subject = 'I need help', accountId = a.id);
try{
insert c;
system.debug('Success');
} catch(dmlexception e){
// ************ Assume the CASE insert FAILED ***********
// If DML failed, ends up here
system.debug('Error inserting case: ' + e);
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Could not insert Case record. Error: ' + e));
// Upon error roll back the database
// This line would "undo" the account insert above and once the user sees the error message on screen we can
// feel confident that the database is not soiled with invalid information. In this example we are preventing
// accounts without a case from being inserted on each attempt.
Database.rollback(sp); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<
// You should fix your sobject variables now, they may have invalid Ids, look for Part 2 of this blog article to explain.
// You may also need to handle the pagereference / redirect conditionally here, typically just refresh the page to see errors which means returning null.
}
// If we get this far in code, something may have failed and been caught above, or everything worked.
system.debug('Potential Success, conditional refresh of page or redirect etc.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment