class Dry::Monads::Try
Represents a value which can be either success or a failure (an exception). Use it to wrap code that can raise exceptions.
@api public
Constants
- DEFAULT_EXCEPTIONS
@private
Attributes
@return [Exception] Caught exception
Private Class Methods
Safely runs a block
@example using Try
with [] and a block (Ruby 2.5+)
include Dry::Monads::Try::Mixin def safe_db_call Try[DatabaseError] { db_call } end
@param exceptions [Array<Exception>] @return [Try::Value,Try::Error]
# File lib/dry/monads/try.rb, line 68 def [](*exceptions, &block) raise ArgumentError, "At least one exception type required" if exceptions.empty? run(exceptions, block) end
Wraps a value with Value
@overload pure(value, exceptions = DEFAULT_EXCEPTIONS
)
@param value [Object] value for wrapping @param exceptions [Array<Exceptions>] list of exceptions to rescue @return [Try::Value]
@overload pure(exceptions = DEFAULT_EXCEPTIONS
, &block)
@param exceptions [Array<Exceptions>] list of exceptions to rescue @param block [Proc] value for wrapping @return [Try::Value]
# File lib/dry/monads/try.rb, line 47 def pure(value = Undefined, exceptions = DEFAULT_EXCEPTIONS, &block) if value.equal?(Undefined) Value.new(DEFAULT_EXCEPTIONS, block) elsif block.nil? Value.new(exceptions, value) else Value.new(value, block) end end
Invokes a callable and if successful stores the result in the {Try::Value} type, but if one of the specified exceptions was raised it stores it in a {Try::Error}.
@param exceptions [Array<Exception>] list of exceptions to rescue @param f [#call] callable object @return [Try::Value, Try::Error
]
# File lib/dry/monads/try.rb, line 28 def run(exceptions, f) Value.new(exceptions, f.call) rescue *exceptions => e Error.new(e) end
Private Instance Methods
Returns true for an instance of a {Try::Error} monad.
# File lib/dry/monads/try.rb, line 82 def error? is_a?(Error) end
Returns self.
@return [Try::Value, Try::Error
]
# File lib/dry/monads/try.rb, line 90 def to_monad self end
Returns true for an instance of a {Try::Value} monad.
# File lib/dry/monads/try.rb, line 76 def value? is_a?(Value) end