Result: maintaining failure trace in .or()

Let’s say I have some result that I want to conditionally change failures to successes. I can do this:

result.or { |error| error.recoverable? ? Success(default) : Failure(error) }

This works, except that I lose the original trace from the failure case in result.

Is there a good way to preserve this?

Thanks!

I won’t say it’s a good way, but you can preserve this. It’s the second argument to Failure#initialize .

result.or { |error| error.recoverable? ? Success(default) : Failure.new(error, result.trace) }

However, I think there is a more elegant solution for this

result.or { |err| err.recoverable? ? result.flip : result }

or let’s say you don’t want to have to reference an intermediate result variable, that could be inconvenient

result.then { |res| res.failure&.recoverable? ? res.flip : res }
1 Like

This is helpful! Thanks!