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

Salesforce Spring ’26 release top features by TrueSolv

Salesforce Spring 26 Release TrueSolv Blog

Spring 26 is the kind of release that changes Monday morning operations more than it changes your homepage for good. We at TrueSolv noticed fewer gaps between intent and execution, stronger defaults around integrations, and better tools to keep automation and data governance under control. The fastest way to get value is to treat Spring 26 as a portfolio of operational upgrades. Pick a few that reduce friction for revenue and service teams, pick a few that reduce risk for security and integration owners, then make them part of your quarterly delivery plan. Here’s top new features that we found the most interesting and useful so far. Sales Cloud and revenue teams Sales Workspace plus account and prospecting enhancements Sales Workspace is a new hub that brings together guidance, analytics, and execution so reps spend less time hunting for context. Account Management and Prospecting updates focus on keeping accounts current and keeping pipeline full, including prioritized prospects visible in CRM and Slack. Engagement improvements with review controls Engagement Enhancements add the Review Before Send workflow and the ability to send emails from a seller’s address, which is useful when you want scale without letting automation send risky messaging unchecked. Revenue Management improvements Spring ’26 also brings updates across revenue related capabilities such as omni channel selling enhancements and billing service assistance, aimed at reducing manual handling of routine billing questions and quote flows. Service operations Proactive service and signal based management Proactive Service is designed to catch issues earlier and scale resolution guidance before escalation. Customer Signals in Command Center brings monitoring into the place where service leaders already manage operations. Knowledge upkeep that does not rely on hero admins Self Learning Knowledge analyzes service interactions to surface knowledge gaps and suggest updates, so the content stays usable as your support volume and channels grow. IT service starter pack The IT Service Domain Pack includes customizable agents, 100 plus workflows, and 100 plus service catalog items, which can shorten time to value for IT service management patterns. Data 360 and enterprise search Faster path from connection to activation Agentic Setup and Data Management is positioned to orchestrate the Data 360 pipeline with suggestions and more guided setup, aimed at speeding up connection to activation while maintaining control. Data lineage you can actually use in governance conversations Salesforce Unified Lineage provides a visual view of data movement and dependencies from source to activation, which helps when metrics change and leadership asks where the number came from. Enterprise Search and connector expansion Agentic Enterprise Search is designed to surface information across the enterprise from inside the CRM search bar. Data 360 Connector Enhancements include Zero Copy connectors for live warehouse data and connectors for unstructured sources like Box, Guru, YouTube, and Confluence. Security and integrations New Connected Apps creation restricted by default Starting with Spring 26, creation of new Connected Apps is disabled by default. Salesforce is steering new inbound integrations toward External Client Apps. Existing Connected Apps continue to function, but your integration governance model needs an update. What leaders should take from this This is not a UI tweak. It changes how new vendors, internal tools, and partner systems will authenticate going forward, and it forces a healthier inventory of who has access to what. The Salesforce architecture guidance frames this as a security and stability modernization, alongside reducing legacy authentication patterns. What this changes for your business Faster execution in core workflows. Sales and service features focus on removing manual steps and tightening operational loops. Better control over risk. Connected Apps restrictions and security modernization reduce the surface area of unmanaged integrations and legacy auth. Cleaner governance conversations. Unified Lineage and export disclaimers make it easier to answer the two questions leadership always asks, where did this number come from and how do we prevent data mishandling. How to find and enable the key items Start with release readiness and Release Updates Use Setup and search for Release Updates to review items that need preparation or testing in sandbox before enforcement. Enable Error Console Go to Setup, then User Interface, then enable the Error Console option for Lightning Experience error reporting. Add report export disclaimers and dashboard table alignment Go to Setup, then Reports and Dashboards Settings, enable the custom disclaimer for exported reports, and enable applying report settings to dashboard tables. Turn on Sales Workspace Sales Workspace can be turned on from Salesforce Go accessed via the gear icon, then search for Sales Workspace and complete the guided steps. Plan External Client Apps for new inbound integrations In Setup, search for External Client Apps and review External Client App Settings. Salesforce documentation indicates turning on the Allow creation of connected apps setting when needed, while shifting new integrations toward External Client Apps. Use Named Query API where standard queries keep getting rebuilt In Setup, go to Integrations, then Named Query API, define the query, and use the REST resource documentation for external consumption. To make Spring 26 pay off, pick a handful of changes, roll them out with ownership, and measure the impact the same way you measure revenue and service outcomes. We share practical release breakdowns, implementation tips, and short playbooks for Salesforce leaders across our channels. Follow TrueSolv on our social media to learn more about how to make your Salesforce work for your profit. And if you want to feel more confident with your Salesforce we at TrueSolv ready to help you, just drop us a message and we’ll contact you.

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.

Salesforce Code Builder – New Productivity Tools

Salesforce Code Builder – New Productivity Tools

Salesforce announced new tools for developers and admins that can help to innovate faster than ever by building scalable, modern apps through a combination of clicks and code without ever having to sacrifice user experience or crucial security measures.  Code Builder Code Builder is a web-based development environment fully optimized for Salesforce development and powered by Microsoft’s Visual Studio Codespaces. Code Builder is a full-featured version of Visual Studio Code running completely in the browser and backed by a powerful cloud-hosted developer environment. In just one click, you have a full environment without any setup or configuration. Code Builder comes with everything you need to build applications on the Salesforce Platform: Including Salesforce Extensions The Salesforce CLI Git integration It’s authenticated to your current Salesforce org. Every instance of Code Builder is backed by its own powerful Virtual Machine. This means Code Builder will allow you to do everything from simple code edits to Lightning Web Component development and advanced Apex debugging. Salesforce Functions Salesforce Functions is a service that lets developers write code that integrates with their data and events on the Salesforce Platform, and run it on-demand with elastic scale in a serverless environment. It empowers development teams to focus on delivering apps and business logic fast, instead of managing infrastructure. To accelerate app building, developers have the flexibility to innovate using languages they already know. They can quickly build, test, and debug Functions locally using the Salesforce developer tools. Admins or other users can extend their business processes by calling Functions from existing Apex code or low-code tools like Flow or even distribute them as part of AppExchange packages. DevOps Center DevOps Center allow admins and other declarative developers build against source control, collaborate better with programmatic developers, release apps faster, and do so with modern workflows like continuous integration and delivery. DevOps Center allows organizations to continue to prioritize release velocity, simplifying how apps are progressed through development environments from concept to launch, and boosting both the speed and quality of deployments. And since DevOps Center allows you to develop in your traditional sandboxes, you can also take advantage of additional capabilities like Data Mask that anonymize sensitive data in your testing environments — delivering speed without sacrificing trust. Code Builder Features Lightning Web Components Developers can now write, debug, and deploy LWC directly from the browser. Code Builder provides modern development features like code completion, inline documentation, refactoring, linting, and much more. Apex With Code Builder you can do everything in the browser, including using the rich Apex debugging capabilities. Org metadata Code Builder provides access to the full metadata of an org. Using the Org Browser you can open any metadata type for inspection and editing. Once you make changes to your metadata, the change is saved instantly to your org. Application Lifecycle Management Code Builder allow you to connect or create multiple orgs This means that it isn’t limited to the simple editing of org metadata. You can use it to script deployments between multiple orgs and test changes in scratch orgs. SOQL queries SOQL Query Builder allow you to write and execute SOQL queries with an easy to use graphical interface while also allowing for editing the query syntax directly for more advanced features. A powerful developer environment Code Builder is a powerful cloud-hosted developer environment. You can access the command line to run tools like the Salesforce CLI and save files to the disk which are persisted for the next time you come back. Code Builder is in Pilot June 25, 2020 with a limited group of customers. If you’re interested in learning more, please reach out to your Account team at Salesforce. If you’re interested in our articles, follow us on the Linkedin page.

How to fix ‘Bad value for restricted picklist field’ error

How to fix ‘Bad value for restricted picklist field’ error

Users or developers may receive the following error when they attempt to create or update a record in Salesforce: Error: Invalid Data. Review all error messages below to correct your data.‘Bad value for restricted picklist field: PicklistValue’ This error occurs when the picklist field referenced in the error message meets each of the following conditions: