Skip to content
Suggest a correction

Run Record Health Check from Apex

Guide9 min read

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.

  1. Create, activate, and test the Check Set or Check on the record-page card.
  2. 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 the rhc__ prefix, such as rhc__Example_Account_Check_Builder_Guide.
  3. 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.
  4. 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 sharing code.

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.

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.

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.

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);
FactoryRuns
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
MethodDefaultValue
withResultMode(...)EVALUATIONWhat response.results contains. See Result modes.
withEventPublication(...)NONENONE, ACTIONABLE, or ALL. See Publish Platform Events.
withRunId(...)GeneratedText, up to 120 characters, that identifies this run in results, debug logs, and events. When blank, Record Health Check generates one.
withExecutionOrigin(...)APEX_APIThe Source value on published events. Set it only when you write your own async adapter. Values: APEX_API, FLOW, USER_INITIATED, RUN_ON_LOAD, 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.0' 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.

Moderesponse.results containsUse it when
EVALUATIONEvery result, with evaluation onlyCode decides from statuses and values.
EVALUATION_WITH_DISPLAYEvery result, with evaluation and displayCode shows the card’s messages, values, or fix link.
SUMMARYOnly FAIL, UNABLE_TO_EVALUATE, and ERROR resultsCode needs the counts and the records to follow up.

In every mode, response.summary counts all results.

rhc.RecordHealthCheckResponse:

FieldValue
runIdThe Run ID: yours, or the generated one.
recordIdsThe records evaluated, without nulls and repeats.
checkQualifiedApiNamesThe Checks that ran, in the order they ran: by Evaluation Order, with each Prerequisite Check before the Checks that need it.
resultsA list of rhc.RecordHealthCheckResultItem, one per Check per record, filtered by the result mode.
summaryCounts: passed, failed, skipped, unable, and systemError. summary.total() 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:

FieldValue
recordIdThe record.
checkQualifiedApiNameThe Check.
statusPASS, FAIL, SKIPPED, UNABLE_TO_EVALUATE, or ERROR. Compare with the rhc.RecordHealthCheckStatus constants.
severityCRITICAL, WARNING, or INFO, the Check’s Failure Severity, when the status is FAIL.
reasonCodeA code that explains the result, when there is one. See Reason codes.
found, expectedThe compared values, as rhc.RecordHealthCheckValue, when the Check records them.
comparisonOperatorThe operator that compared them, when there is one.
diagnosticId, diagnosticCategory, diagnosticSummary, recommendedActionFor UNABLE_TO_EVALUATE 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:

dataTypeRead
STRING, IDstoredValue
NUMBER, COUNTDecimal.valueOf(storedValue)
BOOLEANstoredValue == 'true'
DATEDate.valueOf(storedValue); the format is yyyy-MM-dd
DATETIMEstoredValue, in UTC as yyyy-MM-ddTHH:mm:ssZ
LISTstoredValues, 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.

StatusMeaningTypical action
PASSThe record meets the requirement.Continue.
FAILThe record does not meet the requirement.Take the business follow-up action.
SKIPPEDThe Check did not apply, or its prerequisite did not pass.Continue, or report separately.
UNABLE_TO_EVALUATEAccess, configuration, or data prevented a reliable answer.Report the Reason Code; fix access or configuration.
ERRORAn unexpected problem stopped the Check.Report the Diagnostic ID for technical investigation.

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:

ProblemException message
The running user lacks the Record Health Check Run custom permissionStarts with NOT_AUTHORIZED:
The record list is nullRecord IDs are required. (rhc.RecordHealthCheckRequest.RecordHealthCheckRequestException)
No active Check Set or Check has the nameCheck Set "<name>" was not found. or Check "<name>" was not found.
The Check Set is inactiveThe selected Check Set is inactive.
A record belongs to a different object than the Check SetThe selected Check Set is for <object>, not <object>.
More than 200 unique record IDsStarts with MAX_RECORDS_PER_SCOPE_EXCEEDED:
More than 25 active Checks in the Check SetStarts with FRAMEWORK_MAX_CHECKS_EXCEEDED:
The request needs more formula evaluations than remainStarts with This request plans
Too few queries, query rows, DML statements, or heap remain in the transactionStarts with TRANSACTION_BUDGET_EXCEEDED:, HEAP_BUDGET_EXCEEDED:, or PLUGIN_SAVEPOINT_BUDGET_EXCEEDED:
An Apex Check changed data, made a callout, sent email, or started a Queueable or future jobStarts with A health check must not change anything.
The diagnostic version is not 2.0UNSUPPORTED_DIAGNOSTIC_VERSION

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.

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);
ValuePublishes
NONENothing.
ACTIONABLEA Result event for each FAIL, UNABLE_TO_EVALUATE, or ERROR result, and a Set Run event per record.
ALLA 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.

LimitValue
Unique records per request200
Active Checks in a Check Set25
Formula evaluations per transaction95, shared by every request in the transaction
Queries, query rows, CPU time, and heapThe 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.

Record Health Check checks the running user’s permission in tests too. Run the code as a user who has Record Health Check User:

@IsTest
private 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.

What you seeWhat to check
NOT_AUTHORIZED:The running user’s Record Health Check User assignment.
... was not found.The exact Qualified API Name, including rhc__ for an installed example, and that it is active.
UNABLE_TO_EVALUATE with CANNOT_EVALUATEThe running user’s access to the fields and records the Check reads. Diagnostics show the exact field.
display is nullUse EVALUATION_WITH_DISPLAY.
No Platform Event arriveswithEventPublication, and whether the transaction committed.
MAX_RECORDS_PER_SCOPE_EXCEEDED:Split the records into requests of 200, or use Batch Apex.