From 6a0ab775a87cc8ce59ce98db973eebb8219348c1 Mon Sep 17 00:00:00 2001 From: Shujat Khalid Date: Thu, 8 Aug 2024 14:39:23 +0100 Subject: [PATCH] Able to pull through email info through header --- app/mailers/application_mailer.rb | 19 ++++++++++++ .../anonymous/test_notify_error.text.erb | 1 + spec/mailers/application_mailer_spec.rb | 30 +++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 app/views/anonymous/test_notify_error.text.erb create mode 100644 spec/mailers/application_mailer_spec.rb diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb index e894de7278..630698da85 100644 --- a/app/mailers/application_mailer.rb +++ b/app/mailers/application_mailer.rb @@ -8,4 +8,23 @@ class ApplicationMailer < Mail::Notify::Mailer "GOVUK_NOTIFY_TEMPLATE_ID_APPLICATION", "95adafaf-0920-4623-bddc-340853c047af", ) + + rescue_from Notifications::Client::RequestError do + # WARNING: this needs to be a block, otherwise the exception will not be + # re-raised and we will not be notified via Sentry, and the job will not retry. + # + # @see https://github.com/rails/rails/issues/39018 + if respond_to?(:headers) + binding.break + email = Email.find(headers['email-log-id'].to_s) + email.update!(delivery_status: 'notify_error') + end + + raise + end + + def notify_email(headers) + headers = headers.merge(rails_mailer: mailer_name, rails_mail_template: action_name) + view_mail(GOVUK_NOTIFY_TEMPLATE_ID, headers) + end end diff --git a/app/views/anonymous/test_notify_error.text.erb b/app/views/anonymous/test_notify_error.text.erb new file mode 100644 index 0000000000..5110cc44ff --- /dev/null +++ b/app/views/anonymous/test_notify_error.text.erb @@ -0,0 +1 @@ +This is used by the ApplicationMailer spec. diff --git a/spec/mailers/application_mailer_spec.rb b/spec/mailers/application_mailer_spec.rb new file mode 100644 index 0000000000..d38b120d3d --- /dev/null +++ b/spec/mailers/application_mailer_spec.rb @@ -0,0 +1,30 @@ +require 'rails_helper' + +RSpec.describe ApplicationMailer, :sidekiq do + describe '.rescue_from' do + fake_mailer = Class.new(ApplicationMailer) do + self.delivery_method = :notify + self.notify_settings = { + api_key: 'not-real-e1f4c969-b675-4a0d-a14d-623e7c2d3fd8-24fea27b-824e-4259-b5ce-1badafe98150', + } + + def test_notify_error + notify_email( + to: 'test@example.com', + subject: 'Some subject', + ) + end + end + + it 'marks errors as failed and re-raises the error' do + stub_request(:post, 'https://api.notifications.service.gov.uk/v2/notifications/email') + .to_return(status: 404) + + expect { + fake_mailer.test_notify_error.deliver_now + }.to raise_error(Notifications::Client::NotFoundError) + + expect(Email.last.delivery_status).to eql('notify_error') + end + end +end