Apex API Reference
Usage Principles
- Log exceptions with context and correlation IDs.
- Prefer partial-success APIs for bulk operations.
- Keep production code free of leftover debug noise.
- Use dependency boundaries so code remains testable.
Database Class
Database.upsert(records, externalIdField, allOrNone)
Database.UpsertResult[] results = Database.upsert(
contacts,
Contact.ExternalId__c,
false
);
Use for idempotent synchronization and row-level failure handling.
Database.update(records, allOrNone)
Database.SaveResult[] results = Database.update(records, false);
Use when you need partial success and detailed per-record errors.
EventBus (Platform Events)
EventBus.publish(events)
List<Database.SaveResult> publishResults = EventBus.publish(
new List<My_Event__e>{ new My_Event__e(Key__c = 'ABC') }
);
Always inspect publish results and log failures.
Async Interfaces
Queueable
Id jobId = System.enqueueJob(new ReconciliationQueueable(recordIds));
Use for composable async jobs, callouts, and controlled chaining.
Database.Batchable
Id batchId = Database.executeBatch(new NightlyBatch(), 200);
Use for large-volume processing with chunked execution.
Schedulable
Id schedId = System.schedule('Nightly Recalc', '0 0 2 * * ?', new NightlyScheduler());
Use for time-based orchestration and recurring jobs.
HTTP Callouts
HttpRequest + Named Credential
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:MyNamedCredential/v1/resource');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(payloadJson);
HttpResponse res = new Http().send(req);
Set explicit timeouts and handle non-2xx responses consistently.
Testing APIs
Test.startTest() / Test.stopTest()
Use to reset limits and flush async work for assertions.
Test.startTest();
System.enqueueJob(new ReconciliationQueueable(ids));
Test.stopTest();
Test.setMock(HttpCalloutMock.class, mock)
Use for deterministic callout tests without network dependency.
System.runAs(user)
Use to validate sharing/security behavior for different user contexts.
Error Handling Pattern
try {
// operation
} catch (DmlException e) {
// log + map to domain-specific exception
throw e;
}
Map low-level exceptions to actionable domain errors where appropriate.