How To Debug Apex Code Without Losing Your Mind

How to debug Apex code in Salesforce Developer Console and VS Code

Apex does not come with a pause button. There is no traditional breakpoint that stops execution and lets you poke around. What Salesforce gives you instead is a set of logging, inspection, and replay tools that, used well, make finding the problem faster than most developers expect. This guide covers the practical workflow from first error to confirmed fix, with examples at each step. Step 1: read the error before you do anything else Most debugging sessions start with someone jumping straight into the code. The error message is still the fastest path to the problem, and it is worth reading carefully before opening any tool. Salesforce Apex errors typically tell you the class name, the line number, and the exception type. A System.NullPointerException at line 42 in AccountTriggerHandler is telling you exactly where to look. A System.LimitException: Too many SOQL queries: 101 is telling you the problem is structural, not a typo. The three most common Apex exceptions and what they signal: NullPointerException A variable you expected to have a value is null. Usually means a query returned no records, or an object field was never set. LimitException A governor limit was hit. SOQL inside a loop is the classic cause of the 101 SOQL queries error. DmlException A database operation failed. Required field missing, validation rule violation, or duplicate record are the usual culprits. Step 2: add System.debug() to trace what is happening System.debug() is the starting point for most Apex debugging. It writes output to the debug log, which you can then read to understand what your code was actually doing at each point. Place debug statements before and after the line you suspect is failing, and log the values of the variables involved. Basic System.debug() usage Account acc = [SELECT Id, Name, OwnerId FROM Account WHERE Id = :accountId LIMIT 1]; System.debug('Account retrieved: ' + acc); System.debug('Owner ID: ' + acc.OwnerId); The LoggingLevel parameter controls how much noise you produce in the log. Use LoggingLevel.DEBUG for general tracing and LoggingLevel.ERROR for conditions that should never occur. Using log levels to filter output System.debug(LoggingLevel.DEBUG, 'Entering processAccount method'); System.debug(LoggingLevel.ERROR, 'Account is null – this should not happen'); System.debug(LoggingLevel.FINEST, 'Loop iteration value: ' + i); Setting the log level to FINEST captures everything. That is useful when you have no idea where the problem is. Once you narrow the location down, reduce it to DEBUG to keep the log readable. Step 3: enable debug logs and read them in Developer Console Debug statements only appear if logging is active for the user running the code. Setting up a trace flag takes two minutes and is required before any logging will appear. Go to Setup search for Debug Logs in the Quick Find box. Click New select the user you want to trace, set an expiry time, and choose a debug level. Start with SFDC_DevConsole if you are not sure which level to use. Reproduce the issue trigger the code by running the action that causes the error. Open Developer Console go to the Logs tab and double-click the most recent log entry. Use the filter type the class or method name you are debugging to isolate relevant lines from the noise.   The log output includes a timestamp, event type, and the message from your System.debug() call. What to look for: USER_DEBUG lines contain your System.debug() output SOQL_EXECUTE lines show every query that ran and how many rows it returned DML_BEGIN and DML_END wrap every database operation CUMULATIVE_LIMIT_USAGE near the end of the log shows governor limit consumption Step 4: use Execute Anonymous to isolate and test When you want to test a specific piece of logic without triggering the full context of a trigger or flow, Execute Anonymous is the fastest tool available. It runs Apex directly in the org against real data, and the debug log appears immediately. Open it from Developer Console under Debug, then Open Execute Anonymous Window. Testing a query and inspecting results in isolation Id testAccountId = '0015g00000XXXXXX'; List<Account> accts = [ SELECT Id, Name, AnnualRevenue, OwnerId FROM Account WHERE Id = :testAccountId ]; System.debug('Records found: ' + accts.size()); if (!accts.isEmpty()) { System.debug('Account name: ' + accts[0].Name); System.debug('Annual revenue: ' + accts[0].AnnualRevenue); } This approach lets you confirm whether the data you expect to be there actually is, before assuming the logic is wrong. Many debugging sessions end here because the data was the problem, not the code. Step 5: use Apex Replay Debugger for complex flows For situations where System.debug() alone is not enough, VS Code’s Apex Replay Debugger lets you step through a captured debug log line by line, inspect variable values at each point, and set breakpoints on specific lines without stopping real execution. This is the closest Apex gets to a traditional debugger, and it is free with the Salesforce Extension Pack for VS Code. Open the Apex class or trigger in VS Code click in the gutter to the left of the line numbers to set a breakpoint. Enable the replay debugger open the Command Palette with Ctrl+Shift+P and run SFDX: Turn On Apex Debug Log for Replay Debugger. Reproduce the issue in the org trigger the code that is failing. Fetch the log Command Palette, then SFDX: Get Apex Debug Logs, and select the relevant log. Launch the replay Command Palette, then SFDX: Launch Apex Replay Debugger with Current File. Execution will pause at your breakpoints and you can inspect variable values in the VS Code sidebar.   Replay Debugger does not run code again. It replays a captured log, so the variable values you see reflect what actually happened during the original execution. This is exactly what makes it useful for reproducing intermittent bugs. Step 6: identify governor limit issues before they become production problems Governor limits are the category of Apex errors that can reach production undetected in low-volume testing and then fail at scale. The most common is the 101 SOQL queries limit caused by queries inside loops. The pattern that causes 101

How Upload Custom Metadata Type from CSV

How to upload custom metadata type records from CSV in Salesforce

Salesforce said no to Data Loader for custom metadata. Here is what actually works. The first time most admins try to load custom metadata type records in bulk, they open Data Loader out of habit. Data Loader does not support custom metadata types. It never has. That is not an oversight. Custom metadata lives in the metadata layer, not the data layer, which means the tools built for data records simply do not apply. The good news is that there are three approaches that do work, and choosing the right one depends on who is doing the loading and how many records are involved. Why custom metadata types are different Custom metadata types store configuration, not transactional data. Validation rules, routing logic, feature flags, mapping tables, rate cards, and similar reference data all live there. Because they are part of the metadata layer, they are deployable between environments, version-controllable, and accessible in formula fields and flows without additional SOQL queries. That architecture is what makes them useful. It is also what makes bulk loading feel counterintuitive at first. You are not inserting records into a database table. You are deploying metadata through the Metadata API. Once that distinction is clear, the available approaches make considerably more sense. There are three reliable ways to load custom metadata type records from a CSV file. The Custom Metadata Loader app, the Salesforce CLI, and a Flow-based component. Each has a different profile in terms of setup effort, permissions required, and practical limits. Option one: the Custom Metadata Loader app The Custom Metadata Loader is a Salesforce-built tool available on GitHub. It was the standard approach before CLI commands became generally available, and it remains the most admin-friendly option for teams not using a developer toolchain. Setup requires a one-time deployment to the org, after which admins with the correct permission set can load records directly from the UI without touching a terminal. The tool uses the Metadata API in the background and can process up to 200 records per call. The setup process follows these steps: Download the Custom Metadata Loader from the Salesforce GitHub repository and create a zip file from the contents of the custom_md_loader directory. The package.xml file should sit at the top level of the zip, not inside a subfolder. Log in to Workbench with the target org credentials, navigate to Migration and then Deploy, and upload the zip file. Once deployed, go to Setup and assign the Custom Metadata Loader permission set to anyone who will use the tool. Open the Custom Metadata Loader app from the App Picker and configure Remote Site Settings if prompted.   To load records, prepare a CSV file where the header row contains the API names of the custom metadata type fields. The Label or DeveloperName field is required in every file. Either one is sufficient to identify new records or update existing ones. If the org has a namespace, include the namespace prefix in the field API names in the CSV header. Duplicate Label or DeveloperName entries in the file will result in only the last row being processed. Upload the CSV file, select the corresponding custom metadata type from the dropdown, and click Create/Update. The tool will confirm how many records were processed and flag any errors in the output. The 200-record limit per call is worth noting. For larger datasets, the file needs to be split. For very large migrations, the CLI approach removes this constraint entirely. Option two: Salesforce CLI As of Summer 2020, the Salesforce CLI includes dedicated commands for custom metadata types. This is the approach Salesforce now recommends for development workflows, and it has no record limit. The relevant command for inserting records from a CSV file is: sf cmdt generate records –csv CountryMapping.csv –type-name CountryMapping__mdt This command generates the custom metadata record files locally in the project directory. The records then need to be deployed to the org using the standard deploy command: sf project deploy start This command generates the custom metadata record files locally in the project directory. The records then need to be deployed to the org using the standard deploy command: The CSV file format follows the same rules as the Loader approach. The header row must contain field API names, and either Label or DeveloperName is required. The DeveloperName value can only contain alphanumeric characters and underscores, must begin with a letter, and cannot end with an underscore or contain two consecutive underscores. Spaces in name values should be replaced with underscores. The CLI approach fits naturally into a DevOps pipeline. Records can be committed to version control, reviewed before deployment, and promoted through environments using the same workflow as any other metadata change. For teams already running a source-driven development model, this is the more sustainable long-term approach. The steps for a first-time setup follow this sequence: Install the Salesforce CLI and authenticate with the target org using sf org login. Create or open an existing SFDX project in VS Code. Retrieve the custom metadata type definition from the org so the project is aware of its field structure. Prepare the CSV file with the correct field API names in the header row. Run the cmdt generate records command, review the generated files in the CustomMetadata folder, and deploy to org. Option three: a Flow-based screen component For orgs where neither GitHub deployment nor CLI access is practical, a third option exists in the form of a community-built Flow screen component. This approach allows admins to upload a CSV directly from a screen flow in the org, with no external tooling required. The component was created by Salesforce MVP Narender Singh and is available through the UnofficialSF community. It handles the Metadata API calls internally, so the user experience is simply uploading a file and selecting the metadata type. This approach is most appropriate for one-off loads in environments with restricted developer access or where deploying external tools to the org is not straightforward. It is less

How to develop flexible Apex code for Salesforce

How To Develop Flexible Apex Code For Salesforce

Day-to-day developer work related not only with writing new functionality but updating existing ones. When a developer tasked with adding a new feature to an existing application, the goal is to extend the functionality of that application with new behaviors. Extending software is the introduction of a new behavior by the addition of code. Some applications are flexible to this kind of change, whereas others may fight you tooth and nail! Flexibility is how easily software can adapt to shifting requirements. In an ideal extensible system, adding new behavior involves strictly adding new code without changing existing code. Adding new behavior to an extensible system means adding new classes, methods, functions, or data that encapsulate the new behavior. But because real systems are rarely ideal, you’ll still find yourself needing to make changes to existing code regularly. One of the things that help developers write clean, well-structured, and easily-maintainable code is SOLID principles.

How To Send Custom Desktop/Push Notifications In Salesforce

How To Send Custom Desktop/Push Notifications In Salesforce

Everyone knows that it is so important to send notifications when important events occur. For example, alert an account owner if a new support case is logged while trying to close a deal. Or, send a notification for a unique workflow built entirely with custom objects. Previously, you could send only standard notifications for use cases predefined by Salesforce. Custom notifications allow you to send important information to your users via push to mobile or desktop alerts. Now you can fully customize the notifications to inform users of record information, changes, and updates. Custom notifications will bring relevant information to your users at the right time!

How to fix the caching problem in Salesforce Lighting Component

How to fix the caching problem in Salesforce Lighting Component

Salesforce trying to optimize performance by caching components on the client-side. This is awesome for the end-users because page loads will faster. This is a lot less awesome for developers when developing lightning components because they may think that the code is wrong. Often they have to hit hard refresh a few times while you wait for the cache to clear.

How to Increase Salesforce Governor Limits

How to Increase Salesforce Governor Limits

Salesforce is known as CRM with a lot of Limits. Because Salesforce Apex runs in a multitenant environment, the Apex runtime engine strictly enforces limits so that runaway Apex code or processes don’t monopolize shared resources. If some Apex code exceeds a limit, the associated governor issues a runtime exception that cannot be handled.