Skip to content

Commit

Permalink
Add custom error handler for missing i18n translations
Browse files Browse the repository at this point in the history
  • Loading branch information
steventux committed Mar 19, 2024
1 parent 6c83f3c commit d96c24f
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
13 changes: 13 additions & 0 deletions config/initializers/i18n.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module I18n
class SentryExceptionHandler
def call(exception, _locale, _key, _options)
if Rails.env.production? && exception.is_a?(MissingTranslation)
Sentry.capture_exception(exception)
else
raise exception.respond_to?(:to_exception) ? exception.to_exception : exception
end
end
end
end

I18n.exception_handler = I18n::SentryExceptionHandler.new
23 changes: 23 additions & 0 deletions spec/config/initializers/i18n_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
require "rails_helper"

RSpec.describe I18n::SentryExceptionHandler do
let(:key) { "missing.translation" }

describe "#call" do
it "raises exceptions in non-production environments" do
expect { I18n.translate(key) }.to raise_exception(I18n::MissingTranslationData)
end
context "in production" do
before do
allow(Rails.env).to receive(:production?).and_return(true)
allow(Sentry).to receive(:capture_exception)
end
it "captures the exception in Sentry" do
I18n.translate(key)
expect(Sentry).to have_received(:capture_exception).with(
I18n::MissingTranslation.new(:en, key)
)
end
end
end
end
14 changes: 12 additions & 2 deletions spec/validators/day_month_year_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ class Validatable
end

RSpec.describe DayMonthYearValidator do
# We don't have translations for our Validatable test class
# avoid I18n::MissingTranslationData exceptions by turning off
# I18n.exception_handler for this particular spec.
around do |example|
exception_handler = I18n.exception_handler
I18n.exception_handler = nil
example.run
I18n.exception_handler = exception_handler
end

subject(:validatable) { Validatable.new(attributes) }

describe "#validate" do
Expand Down Expand Up @@ -42,7 +52,7 @@ class Validatable
expect(validatable.errors[:date_attribute]).to include("is invalid")
end
end

context "when the date is negative" do
let(:attributes) { { day: -1, month: "6", year: "1990" } }

Expand Down Expand Up @@ -162,7 +172,7 @@ class Validatable
expect(validatable.errors[:date_attribute].first).to include("missing_day_and_year")
end
end

context "when month and year are missing" do
let(:attributes) { { day: "15", month: nil, year: nil } }

Expand Down

0 comments on commit d96c24f

Please sign in to comment.