Custom Notification
The Custom Notification submodule provides an efficient builder-style API wrapper for Salesforce Custom Notifications (Messaging.CustomNotification). It simplifies building and sending notifications with robust state validation and error isolation.
Documentation
💾 Source Code
Implementation
- The
CustomNotificationManagerclass is a builder class that coordinates the configuration of properties needed to construct a custom notification payload. - Supports dynamic setup for all required fields
- Enforces integrity before sending via
validateState(), throwingIllegalStateExceptionorIllegalArgumentExceptionon invalid/empty keys, missing contents, or if both target record and page reference are set simultaneously - The
SendResultclass wraps the booleanisSuccessresult of the send operation, catching and logging exception details internally to prevent transaction failure
Demos
apex
// Fetch the notification type ID from setup/SOQL
String customNotificationTypeId = [
SELECT Id
FROM CustomNotificationType
WHERE DeveloperName = 'MyNotificationType'
].Id;
// Send custom notification using the builder pattern
SendResult result = new CustomNotificationManager(customNotificationTypeId)
.withTitle('Task Assigned')
.withBody('A new task has been assigned to you. Click to view details.')
.withTargetRecordId('001xx00003Yabcdefg')
.addRecipient(UserInfo.getUserId())
.send();
if (result.isSuccess) {
System.debug('Notification sent successfully!');
} else {
System.debug('Failed to send notification.');
}Benefits
- Builder pattern provides a highly readable and self-documenting syntax compared to multi-line property setter assignment
- Catches exceptions internally during the send cycle, wrapping them in a clean
SendResultobject so that logging/telemetry failures do not abort the parent transaction - Prevents run-time errors by validating field lengths (e.g., body under 750 characters) and ensuring mutually exclusive properties (e.g., target record ID vs page reference) are configured correctly before invocation
- Easily chains single or multiple collections of recipient IDs via sets and lists
