Debugging Salesforce Code with Apex for Visual Studio — Step-by-StepDebugging Apex in Visual Studio can dramatically speed up development, reduce errors, and improve maintainability for Salesforce applications. This step-by-step guide covers setup, common debugging scenarios, practical tips, and troubleshooting so you can debug effectively using Apex for Visual Studio.
What you’ll need
- A Salesforce Developer Edition or a sandbox/org with API access.
- Visual Studio 2022 (or later) installed on your machine.
- Apex for Visual Studio extension (installed from the Visual Studio Marketplace).
- Salesforce credentials (username, password, and security token if required).
- Basic familiarity with Apex, SOQL, and Salesforce metadata.
1. Install and configure Apex for Visual Studio
- Open Visual Studio and go to Extensions → Manage Extensions.
- Search for “Apex for Visual Studio” and click Install. Restart Visual Studio if prompted.
- After installation, open the Apex pane (View → Other Windows → Apex Explorer) or use the extension’s menu.
- Add a Salesforce connection:
- Choose “Add New Org” (Production or Sandbox/Developer).
- Enter username and password + security token if prompted (or use OAuth flow if supported).
- Confirm connection; the extension will retrieve metadata and display org contents in the Apex Explorer.
Quick tip: Use a Developer Edition org for testing debug flows to avoid impacting production data.
2. Retrieve and open Apex code
- In Apex Explorer, navigate to Classes or Triggers.
- Right-click the class/trigger you want to debug and choose “Retrieve” or “Open.”
- The file opens in Visual Studio’s editor with Apex syntax highlighting and basic IntelliSense provided by the extension.
3. Understand Salesforce debugging options
Salesforce has several debugging approaches; Apex for Visual Studio integrates with a subset:
- System.debug logs — lightweight, used for simple prints.
- Debug logs with breakpoints — Apex interactive debugging (requires a debug session, typically only available via dedicated debuggers or using Salesforce’s Apex Replay Debugger).
- Apex Replay Debugger — replays logs locally with breakpoints; requires capturing a detailed debug log and using a compatible replay tool.
- Remote debugging / Live debugging — some extensions support live breakpoint debugging by establishing a debug session with the org (feature availability depends on the extension and org edition).
Apex for Visual Studio commonly supports retrieving logs and integrating with local replay-style debugging workflows; consult the extension docs for live-debug capabilities specific to your version.
4. Set up logging levels and trace flags
Before capturing useful logs, configure trace flags to include sufficient detail:
- In Setup (Salesforce), search “Debug Logs” → “Debug Logs” or “Trace Flags.”
- Add a new trace flag for the user who runs the code (or use the Apex extension if it provides trace flag management).
- Set the logging level for categories to at least:
- Apex Code: FINEST or DEBUG
- Apex Profiling: INFO or FINE
- Callout, Workflow, Validation, System: INFO or DEBUG as needed
- Save the trace flag. The org will now record verbose logs for that user until the trace flag expires.
Note: FINEST logs grow quickly; only enable them for short captures.
5. Reproduce the issue and capture logs
- Perform the action that triggers the Apex code: run a test, invoke via UI, call through API, or run from anonymous Apex.
- In Apex Explorer or Setup → Debug Logs, find the new log entry. Download or open it in Visual Studio.
- If your extension supports it, open the log with the Replay Debugger or log viewer.
6. Using the Apex Replay Debugger (if available)
Apex Replay Debugger allows setting breakpoints and stepping through code using a debug log as the execution trace.
- Capture a detailed log with the trace flags set as above.
- Open the log in Visual Studio and choose “Open with Apex Replay Debugger” (or similar command).
- Set breakpoints in your Apex source. The replay debugger will map log events to source lines.
- Use step commands:
- Step In — go into method calls
- Step Over — execute the current line
- Step Out — finish current method
- Inspect variables, heap details, SOQL query results, and execution context shown by the debugger.
Limitations: replay debugging is read-only — you cannot change state on the org, only inspect the recorded execution.
7. Classic debug with System.debug and log analysis
When live or replay debugging isn’t available, System.debug statements remain powerful:
- Add targeted System.debug(…) statements to log variable values, method entry/exit, or conditional branches.
- Re-deploy the class/trigger (via the extension).
- Reproduce the scenario to generate logs and analyze them in Visual Studio’s log viewer.
- Remove or lower the verbosity of debug statements after fixing the issue to avoid noisy logs.
Example:
System.debug(LoggingLevel.DEBUG, 'Order processing started for Id=' + orderId); System.debug(LoggingLevel.INFO, 'Query result size=' + results.size());
8. Debugging triggers and asynchronous code
Triggers:
- Use test classes or UI actions to invoke triggers.
- In logs, find the trigger’s execution by searching for the trigger name or the class name of called handlers.
- Ensure trigger contexts (Trigger.isInsert, Trigger.isBefore, etc.) are understood.
Asynchronous (future, Queueable, Batch, Scheduled):
- These run in separate transactions — set trace flags for the user that enqueues or runs them.
- For Batch Apex, enable logging for each execute() chunk.
- For Queueable/future, capture logs after the job runs; consider using debug statements within the asynchronous class.
9. Unit tests and debugging framework
- Write focused Apex test methods to reproduce logic paths. Use Test.startTest()/Test.stopTest() around asynchronous calls to ensure execution occurs within the test context.
- Run tests from Visual Studio (Apex Explorer → right-click test class → Run Tests) or from Salesforce UI.
- View test logs and code coverage results.
- Use assert statements to validate expected behavior and fail fast when logic deviates.
Example pattern:
@isTest static void testProcessOrder() { // setup data Test.startTest(); // call method or enqueue job Test.stopTest(); // assert results }
10. Common debugging scenarios and solutions
- NullPointerException: Add safety checks, log variable states before use, and write unit tests to cover null cases.
- SOQL limits / Too many SOQL queries: Inspect logs for “Too many SOQL queries” and refactor to bulkify (move queries outside loops, use collections).
- DML limits: Check for unnecessary DML inside loops; batch DML operations.
- Incorrect data returned: Log SOQL results and confirm WHERE clauses and sharing rules.
- Test flakiness: Use isolated test data, avoid dependencies on org data, and run Test.startTest()/Test.stopTest().
11. Best practices
- Use meaningful System.debug messages with LoggingLevel to control verbosity. Do not leave verbose debug logs in production code.
- Prefer unit tests + replay debugging over ad-hoc prints for reproducible debugging.
- Keep classes small and single-responsibility to make tracing logic easier.
- Bulkify code to handle many records; always test with larger datasets.
- Review governor limits in logs to preempt runtime failures.
- Use code versioning (Git) and deploy via CI/CD rather than manual edits in production orgs.
12. Troubleshooting the extension
- If Apex for Visual Studio fails to connect:
- Verify credentials and security token.
- Check org IP restrictions and enable OAuth if needed.
- Look for extension updates or Visual Studio compatibility issues.
- If logs don’t appear:
- Confirm trace flags are active for the executing user.
- Ensure the code path actually ran (add a lightweight System.debug).
- If breakpoints don’t map correctly in replay debugger:
- Make sure the debug log corresponds to the exact deployed source version.
- Re-retrieve metadata to sync source files with org code.
13. Example debugging session (concise walkthrough)
- Install extension and connect to Dev org.
- Set trace flags: Apex Code = FINEST.
- Add System.debug before a suspect method, deploy.
- Trigger the action in UI; download the debug log.
- Open the log with Replay Debugger; set breakpoints and step through to identify incorrect variable value.
- Fix code, write a unit test covering the case, run tests, confirm pass and adequate coverage, then deploy.
14. Resources and further reading
- Apex language reference (Salesforce docs)
- Official Apex Replay Debugger guide
- Apex best practices (bulkification, limits)
- Apex for Visual Studio extension documentation
Summary: With the Apex for Visual Studio extension, combine targeted System.debug statements, trace flags, replay debugging, and solid unit tests to efficiently find and fix issues in Apex. Reproduce problems, capture detailed logs, and use the replay or log viewer to inspect execution flow, variables, and governor limits.
Leave a Reply