Exceptions should be qualified with their modules just like classes

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the ruby category.

Last Updated: 2024-10-12

I defined the following exception:

module GenerateFinancialTransactionsReportService
  class ReportRow
    class ReportRowError < StandardError; end
  end
end

Then I consumed it at top-level, outside of these modules

rescue ReportRowError => e
  raise e.class, "Raw transaction #{raw_transaction}"
end

When the above code was run, it failed: the constant ReportRowError was not found.

The fix was to fully qualify it, like I would any class in Ruby

rescue GenerateFinancialTransactionsReportService::ReportRow::ReportRowError => e
  raise e.class, "Raw transaction #{raw_transaction}"
end

This should have been obvious to me: an exception behaves mostly like a class.