3

Allow a fallback value to be returned from Rails.error.handle by kmcphillips · P...

 2 years ago
source link: https://github.com/rails/rails/pull/43716
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Summary

Related to #43472 and follow up to #43625.

Problem

Both the Rails.error.handle and Rails.error.record methods pass through the return value from the wrapped block. This allows for uses like:

result = Rails.error.record { Finder.maybe_error }

This works as expected when nothing is raised. In the case of record it will also always work as expected as the re-raise will take over control flow and we do not encounter the return value.

The case for handle is less intuitive. Consider:

item = Rails.error.handle { Item.find_or_initialize }
product = Rails.error.handle { ProductService.search(params) }

Both cases, if the block raises, it will return nil. Expected behaviour in the first case is that it should always return a value, and in the second case nil implies nothing matches the search. Meaning, the nil returned from the rescue and the nil returned from the block are ambiguous.

Solution

Allow an optional fallback: parameter to be passed to handle that is returned when a raise is handled. This could be a null object, a default value, or some kind of flag differentiating from a nil return.

user = Rails.error.handle(fallback: User.anonymous) do
  User.find_by(params)
end

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK