Activity › Forums › Salesforce® Discussions › What are the Exception handling types in sfdc except try catch block?
-
What are the Exception handling types in sfdc except try catch block?
Posted by Manpreet on April 13, 2017 at 4:21 PMWhat are the Exception handling types in sfdc except try catch block?
Saurabh replied 9 years, 2 months ago 2 Members · 1 Reply -
1 Reply
-
Hi Manpreet
All exceptions support built-in methods for returning the error message and exception type. In addition to the standard exception class, there are several different types of exceptions
Visualforce
If you have a custom controller or controller extension for a Visualforce page, you can handle exceptions just as in the examples above. To show the error on a Visualforce page, you can use the ApexPages.message class to create a message for display. Here’s an example of a message created in a controller:ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,’my error msg’);
ApexPages.addMessage(myMsg);Sending an Email on exception
In addition to displaying the message to the user via page messages, you can also notify the developer by email if you like. Here’s an example:try{
update account;
} catch (DMLException e){
ApexPages.addMessages(e);Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {‘developer@acme.com’};
mail.setToAddresses(toAddresses);
mail.setReplyTo(‘developer@acme.com’);
mail.setSenderDisplayName(‘Apex error message’);
mail.setSubject(‘Error from Org : ‘ + UserInfo.getOrganizationName());
mail.setPlainTextBody(e.getMessage());
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}You could use this technique to ensure that error messages are sent to an error mailing list for example.
Logging in a custom object
If you get enough emails already, another option would be to use a future method to write a custom object that could catch the error details. Your try-catch would look something like this:
try{
throw new MyException(‘something bad happened!’);
} catch (MyException e){
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,’my error msg’);
futureCreateErrorLog.createErrorRecord(e.getMessage());
}Your future class would look something like this.
global class futureCreateErrorLog {
@future
public static void createErrorRecord(string exceptionMessage){
myErrorObj__c newErrorRecord = new myErrorObj__c();
newErrorRecord.details__c = exceptionMessage;
Database.insert(newErrorRecord,false);
}
}For more information about Exception in salesforce you can refer to this link:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_exception_methods.htm
For more information about Exception handling in salesforce you can refer to this link:https://developer.salesforce.com/page/An_Introduction_to_Exception_Handling
Hoping this may help you:
Log In to reply.