When sending push notifications, several errors can occur. The most common are Unauthorized and Expired errors. These happen when a subscription becomes invalid, often due to changes in the browser or user actions like disabling notifications.
Here’s how we can handle these errors:
# app/models/web_push_subscription.rb
class WebPushSubscription < ApplicationRecord
# …
def deliver_payload(data)
WebPush.payload_send(
message: data.to_json,
endpoint: endpoint,
p256dh: p256dh,
auth: auth,
vapid: {
public_key: ENV.fetch("VAPID_PUBLIC"),
private_key: ENV.fetch("VAPID_PRIVATE")
}
)
rescue WebPush::ExpiredSubscription
Rails.logger.info "Removing expired WebPush subscription"
destroy
rescue WebPush::Unauthorized
Rails.logger.info "Removing unauthorized WebPush subscription"
destroy
end
end
Since there’s no way to fix an invalid, unauthorized, or expired subscription, the example above simply removes it. However, you might consider marking the subscription as inactive instead. This approach allows you to investigate issues later or retry the subscription under specific conditions.
By handling these errors gracefully, you’ll keep your notifications reliable and avoid unnecessary retries.