Run the circuit as with #run, but return a Result
This is syntax sugar for running a circuit and rescuing an error
Examples:
result = Faulty.circuit(:api).try_run do api.get end response = if result.ok? result.get else { error: result.error.message } end
# The Result object has a fetch method that can return a default value # if an error occurs result = Faulty.circuit(:api).try_run do api.get end.fetch({})
Parameters:
A cache key, or nil if caching is not desired
Yields:
The block to protect with this circuit
Returns:
A result where the ok value is the return value of the block, or the error value is an error captured by the circuit.
Raises:
If the block raises an error not in the error list, or if the error is excluded.
269 270 271 272 273
# File 'lib/faulty/circuit.rb', line 269 def try_run(**options, &block) Result.new(ok: run(**options, &block)) rescue FaultyError => e Result.new(error: e) end