Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    • Building a Dynamic Tree Grid in Lightning Web Component
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, August 2
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    SalesforceCodex
    Home»Salesforce»Exception Logging in Custom Object : Salesforce Apex

    Exception Logging in Custom Object : Salesforce Apex

    Dhanik Lal SahniBy Dhanik Lal SahniSeptember 8, 2018Updated:January 30, 20227 Comments3 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Exception Logging in Custom Object : Salesforce Apex
    Share
    Facebook Twitter LinkedIn Pinterest Email

    While working on salesforce implementation, we should log exception somewhere in our system. This will help in identifying issue as well as we required it for enhancing our current system.
    We can use salesforce debug log but this we have check each log record one by one to see some specific apex class issue.

    Let us see how to put custom exception logging in salesforce application. Below are steps to create custom logging :-
    1. Create Custom Object
    2. Create Apex class for Exception logging
    3. Use that exception class in your code.

    1. Create Custom Object :
    Let us create new custom object in our salesforce application. Custom object name and fields details are as below image.

    Object Name : CustomException
    Fields detail:

    Field Name Field API Name Type
    ClassName ClassName__c Text(255)
    Exception Message Exception_Message__c Long Text Area(32768)
    Exception Type Exception_Type__c Text(255)
    Govt Limit in Executing Code Govt_Limit_in_Executing_Code__c Long Text Area(32768)
    Line Number Line_Number__c Number(18, 0)
    MethodName MethodName__c Text(255)
    Related To Number Related_To_Number__c Text(255)
    StackTrace StackTrace__c Long Text Area(32768)

    2. Create Apex class for Exception
    We have to create apex class which will extend Exception class. We will implement our code logic in this class.
    Overloaded method LogException with different parameter is created. First method will log any anonymous exception and second method will log exception with record id for which exception is logged.

    public class HandleCustomException extends Exception {
        
        public static void LogException(Exception e)
        {
            LogException(e,'');
        }
        
        // Log Exception in CustomException object. 
        // relatedToId : Case/object for which this error in logged.
        public static void LogException(Exception e,string relatedToId)
        {
            try
            {
    		String stackTrace = e.getStackTraceString().substringBefore('\n');
    		String className = stackTrace.substringAfter('.').substringBefore('.');	
                	String methodName = stackTrace.substringBefore(':').substringAfter(className).substringAfter('.');
                    
                	//Governer Limit of executingQuery 
                    String QueryLimit = '1. SOQL Queries used / SOQL Queries allowed: ' + Limits.getQueries() + '/' + Limits.getLimitQueries();
                    String DMLimit = '2. Number of records queried so far /  Number allowed: ' + Limits.getDmlRows() + '/' + Limits.getLimitDmlRows();
                    String DMLStat = '3. Number of DML statements used so far / Number allowed: ' +  Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements();   
                    String CPUT = '4. Amount of CPU time (in ms) used so far / CPU usage time (in ms) allowed: ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime();
                  
                	//Log information in object
                    CustomException__c exc = new CustomException__c();
                	exc.Related_To_Number__c=relatedToId;
                    exc.Govt_Limit_in_Executing_Code__c = String.format('{0}\n{1}\n{2}\n{3}',new List<string>{QueryLimit, DMLimit,DMLStat,CPUT});
                    exc.Exception_Message__c = e.getMessage();
                    exc.Exception_Type__c = e.getTypeName();
                    exc.Line_Number__c = e.getLineNumber();
                    exc.StackTrace__c = e.getStackTraceString();
                    exc.MethodName__c=methodName;
                    exc.ClassName__c=className;
                    database.insert(exc);            
            } 
            finally{
            }            
        } 
    }
    

    3. Use that exception class in your code.
    Now our apex class is ready to use in our code to handle custom exceptions. For testing, let us create one test class for above apex.

    @isTest
    public class HandleCustomExceptionTest {
        @isTest
        public static void CreateAccount() {
            try {
                Account m = new Account();
                insert m;
            } catch (Exception e) {
                HandleCustomException.LogException(e);
            }    
        } 
    }
    

    Summary :
    if we want to store our application exception, we have to log that in custom object. We can create report/dashboard on that object to see on admin dashboard, so that exception will be tracked.

    Apex logging Error logging in Apex Exception logging in apex
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleHealth Tips for Software Engineers
    Next Article Salesforce Development in Visual Studio Code
    Dhanik Lal Sahni
    • Website

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 2025
    By Dhanik Lal Sahni14 Mins Read

    The Ultimate Guide to Apex Order of Execution for Developers

    July 20, 2025
    View 7 Comments

    7 Comments

    1. Padma Sharma on August 25, 2021 4:39 pm

      I have a requirement to monitor integration issues in Salesforce. I used above code to capture integration issues but getting errors !invalid.list.init and expecting ‘<' but was: '{ , for the line 'exc.Govt_Limit_in_Executing_Code__c = String.format('{0}\n{1}\n{2}\n{3}',new List{QueryLimit, DMLimit,DMLStat,CPUT});'
      Please could you help with this.

      Reply
      • Dhanik Lal Sahni on August 31, 2021 10:06 am

        Hello Padma,

        If format is not working then concatenate these information like QueryLimit+’ ‘+DMLLimit etc or comment that line for testing. If still not working, please connect on telegram or linked-in for 1-2-1 discussion to resolve issue.

        Thank You,
        Dhanik

        Reply
        • Padma Sharma on September 3, 2021 3:20 pm

          Thank you Dhanik!! It’s working now. I have additional requirement to send email with this error message. Please could you help me with this.

          Reply
    2. Randy on January 22, 2022 3:19 pm

      I’m getting the same errors !invalid.list.init and expecting ‘<' but was: '{ , for the line 'exc.Govt_Limit_in_Executing_Code__c = String.format('{0}\n{1}\n{2}\n{3}',new List{QueryLimit, DMLimit,DMLStat,CPUT});'

      Could you kindly assist and supply the final line that is working to solve this error?

      Thank

      Reply
      • Dhanik Lal Sahni on January 30, 2022 7:52 pm

        Hello Randy,
        I have updated the code in that line. Please check now.

        Thank You,
        Dhanik

        Reply
    3. Ars on November 23, 2022 9:44 am

      Hi Dhanik,
      How should I use your code in my Class? Is it just to add extends Exception in my apex class for example like below and inside method to use try catch? My requirement is to build Reusable FrameWork for Error Handling. Please help.

      Reply
      • Dhanik Lal Sahni on November 29, 2022 7:46 pm

        Hello,
        It is a reusable apex. You can use it in a try-catch block as mentioned in the example. If you have any other use case, let us connect on Linkedin.

        Thank You,
        Dhanik

        Reply
    Leave A Reply Cancel Reply

    Ranked #1 Salesforce Developer Blog by SalesforceBen.com
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (150) salesforce apex (52) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    MailChimp

    Expert Salesforce Developer and Architect
    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 10 Salesforce CRM Trends to Watch in 2025 July 18, 2025
    • Discover the Top 10 Salesforce AppExchange Apps to Boost Productivity July 10, 2025
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    Archives
    Categories
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (150) salesforce apex (52) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.