demarches-normaliennes/app/mailers/concerns/mailer_monitoring_concern.rb
Colin Darie ce7e674159 feat(mailer): make errors interceptable by jobs so they will retry
Comme on intercepte chaque `StandardError` pour le monitoring des mails
en erreur, l'erreur n'était plus visible par le job, et les emails
étaient perdus.

A la place on re-raise une autre erreur pour que le job échoue afin de
retry plus tard. Pour ne pas être "avalée" par le rescue_from,
cette erreur doit héritée d'`Exception` plutôt que `StandardError`.

NB: il faudrait parvenir à écrire un test pour vérifier ce comportement.

Pour être vérifié en dev, il faut activer `raise_delivery_errors`
comme en production.
2023-01-17 14:26:11 +01:00

40 lines
1.3 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

module MailerMonitoringConcern
extend ActiveSupport::Concern
included do
before_action :add_dolist_header
# Intercept & log any error, then re-raise so job will retry.
# NOTE: rescue_from order matters, later matchers are tried first.
rescue_from StandardError, with: :log_and_raise_delivery_error
# Dont retry to send a message if the server rejects the recipient address
rescue_from Net::SMTPSyntaxError do |_exception|
message.perform_deliveries = false
end
rescue_from Net::SMTPServerBusy do |exception|
if /unexpected recipients/.match?(exception.message)
message.perform_deliveries = false
else
log_and_raise_delivery_error(exception)
end
end
# mandatory for dolist
# used for tracking in Dolist UI
# the delivery_method is yet unknown (:balancer)
# so we add the dolist header for everyone
def add_dolist_header
headers['X-Dolist-Message-Name'] = action_name
end
def log_and_raise_delivery_error(exception)
EmailEvent.create_from_message!(message, status: "dispatch_error")
Sentry.capture_exception(exception, extra: { to: message.to, subject: message.subject })
# re-raise another error so job will retry later
raise MailDeliveryError.new(exception)
end
end
end