Run Record Health Check from Apex
Run a Check Set or a single Check from Apex code and use the result before the transaction
continues, for example to stop an Account escalation when required data is missing. The
rhc.RecordHealthCheck.evaluate method runs the Checks for up to 200 records and returns a status
for each Check and record.
Use Apex when code needs the result immediately. When the process can be built without code, use the Flow actions instead. When the records do not fit in one request, use Queueable or Batch Apex.
Before you start
Section titled “Before you start”- Create, activate, and test the Check Set or Check on the record-page card.
- Find its exact Qualified API Name, as described in Names and API identities. A Check
Set your organization created has no prefix, such as
Account_Data_Quality. One that installs with the package has therhc__prefix, such asrhc__Example_Account_Check_Builder_Guide. - Assign Record Health Check User to every user whose transactions run the code. It includes
the Record Health Check Run custom permission (
rhc__Record_Health_Check_Run) that every call requires. - Confirm that those users can read the records and fields the Checks use. Record Health Check
reads data with the running user’s access, even from
without sharingcode.
The package’s Apex types have the rhc. namespace prefix in your code, such as
rhc.RecordHealthCheck. That prefix is part of the type name and is unrelated to the rhc__
prefix of installed Check Sets.
Run a Check Set
Section titled “Run a Check Set”public with sharing class AccountEscalationService { public static Set<Id> accountsNeedingReview(List<Id> accountIds) { rhc.RecordHealthCheckResponse response = rhc.RecordHealthCheck.evaluate( rhc.RecordHealthCheckRequest.forCheckSet('Account_Data_Quality', accountIds) );
Set<Id> needsReview = new Set<Id>(); for (rhc.RecordHealthCheckResultItem item : response.results) { rhc.RecordHealthCheckEvaluationResult result = item.evaluation; if (result.status == rhc.RecordHealthCheckStatus.FAIL) { needsReview.add(result.recordId); } else if ( result.status == rhc.RecordHealthCheckStatus.UNABLE_TO_EVALUATE || result.status == rhc.RecordHealthCheckStatus.ERROR ) { // Report result.checkQualifiedApiName, result.reasonCode, and // result.diagnosticId to your monitoring. Do not treat it as FAIL. } } return needsReview; }}The response has one result for each record and each active Check in the Check Set, grouped by
record. FAIL is a normal result, not an exception.
Run one Check
Section titled “Run one Check”rhc.RecordHealthCheckResponse response = rhc.RecordHealthCheck.evaluate( rhc.RecordHealthCheckRequest.forCheck('Billing_City_Is_Populated', accountId));String status = response.results[0].evaluation.status;A single-Check request runs the Check without its Prerequisite Check. Run the Check Set when the prerequisite matters. The Check and its Check Set must both be active.
Build the request
Section titled “Build the request”Create the request with a factory, and then add options with the with... methods. Each method
returns a new request, so chain them:
rhc.RecordHealthCheckRequest request = rhc.RecordHealthCheckRequest .forCheckSet('Account_Data_Quality', accountIds) .withResultMode(rhc.RecordHealthCheckResultMode.SUMMARY) .withEventPublication(rhc.RecordHealthCheckEventPublication.NONE) .withRunId('escalation-' + escalationId);| Factory | Runs |
|---|---|
forCheckSet(qualifiedApiName, recordId) | Every active Check in a Check Set, one record |
forCheckSet(qualifiedApiName, recordIds) | Every active Check in a Check Set, a list of records |
forCheck(qualifiedApiName, recordId) | One active Check, one record |
forCheck(qualifiedApiName, recordIds) | One active Check, a list of records |
| Method | Default | Value |
|---|---|---|
withResultMode(. | EVALUATION | What response. contains. See Result modes. |
withEventPublication(. | NONE | NONE, ACTIONABLE, or ALL. See Publish Platform Events. |
withRunId(. | Generated | Text, up to 120 characters, that identifies this run in results, debug logs, and events. When blank, Record Health Check generates one. |
withExecutionOrigin(. | APEX_ | The Source value on published events. Set it only when you write your own async adapter. Values: APEX_, FLOW, USER_, RUN_, BATCH, QUEUEABLE, SCHEDULED, FUTURE, and AGENT. Choose the one that names what started your code, such as QUEUEABLE in a Queueable job or FUTURE in a future method. |
withDiagnosticContractVersion(. | None | '2. requests the authorized diagnostics described in Authorized diagnostics. Any other value is rejected. |
The record list must not be null. Record Health Check removes null and repeated IDs, and keeps the remaining order.
Result modes
Section titled “Result modes”| Mode | response.results contains | Use it when |
|---|---|---|
EVALUATION | Every result, with evaluation only | Code decides from statuses and values. |
EVALUATION_ | Every result, with evaluation and display | Code shows the card’s messages, values, or fix link. |
SUMMARY | Only FAIL, UNABLE_, and ERROR results | Code needs the counts and the records to follow up. |
In every mode, response.summary counts all results.
Read the response
Section titled “Read the response”rhc.RecordHealthCheckResponse:
| Field | Value |
|---|---|
runId | The Run ID: yours, or the generated one. |
recordIds | The records evaluated, without nulls and repeats. |
checkQualifiedApiNames | The Checks that ran, in the order they ran: by Evaluation Order, with each Prerequisite Check before the Checks that need it. |
results | A list of rhc., one per Check per record, filtered by the result mode. |
summary | Counts: passed, failed, skipped, unable, and systemError. summary. returns their sum. |
The summary has no overall status. To derive one, use the first that applies: ERROR when
systemError > 0, then UNABLE_TO_EVALUATE, FAIL, and PASS for their counts, and SKIPPED
otherwise.
Each rhc.RecordHealthCheckResultItem has evaluation, and display in
EVALUATION_WITH_DISPLAY mode.
item.evaluation is an rhc.RecordHealthCheckEvaluationResult:
| Field | Value |
|---|---|
recordId | The record. |
checkQualifiedApiName | The Check. |
status | PASS, FAIL, SKIPPED, UNABLE_, or ERROR. Compare with the rhc. constants. |
severity | CRITICAL, WARNING, or INFO, the Check’s Failure Severity, when the status is FAIL. |
reasonCode | A code that explains the result, when there is one. See Reason codes. |
found, expected | The compared values, as rhc., when the Check records them. |
comparisonOperator | The operator that compared them, when there is one. |
diagnosticId, diagnosticCategory, diagnosticSummary, recommendedAction | For UNABLE_ and ERROR, an ID to quote to support, a category, a short explanation, and the first recommended fix. |
An rhc.RecordHealthCheckValue has a dataType and the value as text:
dataType | Read |
|---|---|
STRING, ID | storedValue |
NUMBER, COUNT | Decimal. |
BOOLEAN | storedValue == 'true' |
DATE | Date.; the format is yyyy-MM-dd |
DATETIME | storedValue, in UTC as yyyy-MM-ddTHH:mm:ssZ |
LIST | storedValues, a List<String> |
storedValue is null when the value is empty. Decide from status, reasonCode, and these
values, never from display text.
In EVALUATION_WITH_DISPLAY mode, item.display contains the text the card shows:
renderedMessage, renderedFix, foundDisplayValue, expectedDisplayValue,
expectedValueLabel, actionLabel, and actionUrl. A Formula Check’s pass condition, returned as
expectedDisplayValue with the expectedValueLabel Passes when, appears only for users with
diagnostics access. display.adminDetail is present only when the
Check Set has Show Diagnostics selected and the running user has diagnostics access.
Handle every status
Section titled “Handle every status”| Status | Meaning | Typical action |
|---|---|---|
PASS | The record meets the requirement. | Continue. |
FAIL | The record does not meet the requirement. | Take the business follow-up action. |
SKIPPED | The Check did not apply, or its prerequisite did not pass. | Continue, or report separately. |
UNABLE_ | Access, configuration, or data prevented a reliable answer. | Report the Reason Code; fix access or configuration. |
ERROR | An unexpected problem stopped the Check. | Report the Diagnostic ID for technical investigation. |
Handle exceptions
Section titled “Handle exceptions”Some problems stop the whole request and throw an exception instead of returning results. Most of
these exception types are internal to the package, so catch Exception and read the message:
| Problem | Exception message |
|---|---|
| The running user lacks the Record Health Check Run custom permission | Starts with NOT_ |
| The record list is null | Record IDs are required. (rhc.) |
| No active Check Set or Check has the name | Check Set "<name>" was not found. or Check "<name>" was not found. |
| The Check Set is inactive | The selected Check Set is inactive. |
| A record belongs to a different object than the Check Set | The selected Check Set is for <object>, not <object>. |
| More than 200 unique record IDs | Starts with MAX_ |
| More than 25 active Checks in the Check Set | Starts with FRAMEWORK_ |
| The request needs more formula evaluations than remain | Starts with This request plans |
| Too few queries, query rows, DML statements, or heap remain in the transaction | Starts with TRANSACTION_, HEAP_, or PLUGIN_ |
| An Apex Check changed data, made a callout, sent email, or started a Queueable or future job | Starts with A health check must not change anything. |
The diagnostic version is not 2. | UNSUPPORTED_ |
Catch only the exceptions your code can recover from, and let the others reach your normal error monitoring. Salesforce governor limit exceptions cannot be caught.
Publish Platform Events
Section titled “Publish Platform Events”By default, an Apex request publishes nothing. To let a separate Flow, Apex trigger, or integration receive the results, set the publication:
rhc.RecordHealthCheckRequest request = rhc.RecordHealthCheckRequest .forCheckSet('Account_Data_Quality', accountIds) .withEventPublication(rhc.RecordHealthCheckEventPublication.ACTIONABLE);| Value | Publishes |
|---|---|
NONE | Nothing. |
ACTIONABLE | A Result event for each FAIL, UNABLE_, or ERROR result, and a Set Run event per record. |
ALL | A Result event for every result, and a Set Run event per record. |
The value applies directly: the card’s Publish User Run Event and Publish User Result Event
checkboxes do not affect Apex requests. Salesforce delivers the events only if the transaction
commits. Publication never filters response.results. See
Decide when to use Platform Events.
Limits
Section titled “Limits”| Limit | Value |
|---|---|
| Unique records per request | 200 |
| Active Checks in a Check Set | 25 |
| Formula evaluations per transaction | 95, shared by every request in the transaction |
| Queries, query rows, CPU time, and heap | The transaction’s Salesforce governor limits, shared with your own code |
Query, Compare two queries, and Apex Checks run once for all records in the request. Formula Checks use one formula evaluation per formula per record, so a request with several Formula Checks may need fewer records. See Platform limitations.
Test the code
Section titled “Test the code”Record Health Check checks the running user’s permission in tests too. Run the code as a user who has Record Health Check User:
@IsTestprivate class AccountEscalationServiceTest { @IsTest static void returnsAccountsThatFail() { User runner = new User( ProfileId = [SELECT Id FROM Profile WHERE Name = 'Standard User'].Id, LastName = 'Runner', Email = 'runner@example.com', Username = 'runner' + System.currentTimeMillis() + '@example.com', Alias = 'runner', TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US' ); insert runner; insert new PermissionSetAssignment( AssigneeId = runner.Id, PermissionSetId = [ SELECT Id FROM PermissionSet WHERE Name = 'Record_Health_Check_User' AND NamespacePrefix = 'rhc' ].Id );
System.runAs(runner) { Account incomplete = new Account(Name = 'Incomplete Account'); insert incomplete;
Test.startTest(); Set<Id> needsReview = AccountEscalationService.accountsNeedingReview( new List<Id>{ incomplete.Id } ); Test.stopTest();
Assert.isTrue(needsReview.contains(incomplete.Id)); } }}The test assumes that Account_Data_Quality contains a Check that a new Account with only a name
fails, such as a check that Billing City is filled in. Tests read the org’s Custom Metadata
records, so the Check Set must exist in the org where the test runs. Cover a passing record, a failing record, and an unauthorized user who receives the
NOT_AUTHORIZED: exception.
Troubleshoot
Section titled “Troubleshoot”| What you see | What to check |
|---|---|
NOT_ | The running user’s Record Health Check User assignment. |
. | The exact Qualified API Name, including rhc_ for an installed example, and that it is active. |
UNABLE_ with CANNOT_ | The running user’s access to the fields and records the Check reads. Diagnostics show the exact field. |
display is null | Use EVALUATION_. |
| No Platform Event arrives | withEventPublication, and whether the transaction committed. |
MAX_ | Split the records into requests of 200, or use Batch Apex. |