Add custom RuboCop cop for consistent exception logging format#5582
Add custom RuboCop cop for consistent exception logging format#5582
Conversation
Detects `e.message` and `e.class.name` inside rescue blocks and auto-corrects them to `e` and `e.class` within string interpolation. Follow-up to PR #5514 which standardized the format repo-wide. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Fix offense messages: to_s and message have different contracts,
not the same value. The convention prefers to_s (via interpolation).
- Use <<~'RUBY' (non-interpolating) heredocs in specs so #{} is
literal and caret column positions align correctly.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Detect bare #{e} without #{e.class} in the same string inside rescue
blocks. The codebase convention is "#{e.class}: #{e}" — logging the
exception without its class loses context.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
|
✅ Tests 🎉 All green!❄️ No new flaky tests detected 🎯 Code Coverage (details) 🔗 Commit SHA: 0c3dcaf | Docs | Datadog PR Page | Was this helpful? React with 👍/👎 or give us feedback! |
The e.message caret in the combined-patterns test was 1 column too far right (col 26 instead of col 25). Verified all caret positions against actual cop output. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
BenchmarksBenchmark execution time: 2026-04-13 22:55:36 Comparing candidate commit 0c3dcaf in PR branch Found 0 performance improvements and 0 performance regressions! Performance is the same for 45 metrics, 1 unstable metrics.
|
What does this PR do?
Adds
CustomCops::ExceptionMessageCopthat enforces consistent exception logging format inside rescue blocks.The cop detects three patterns:
e.message→ should bee(to_sandmessagehave different contracts;#{e}callsto_s, which is the convention)e.class.name→ should bee.class(Class#to_salready returns the name)#{e}without#{e.class}in the same string → the convention requires the class nameAuto-corrects
e.messageande.class.namewithin string interpolation. The missing-class check flags but does not auto-correct.Motivation:
Follow-up to #5514 which standardized
#{e.class}: #{e}across the codebase. This cop prevents the old patterns from being reintroduced. Suggested by @vpellan during review.Change log entry
None.
Additional Notes:
Only applies to
lib/**/*files (same scope as other custom cops).How to test the change?
bundle exec rake spec:custom_cop