Class: Dry::Monads::Try::Error

Inherits:
Dry::Monads::Try show all
Includes:
RightBiased::Left
Defined in:
lib/dry/monads/try.rb,
lib/dry/monads/maybe.rb,
lib/dry/monads/result.rb

Overview

Represents a result of a failed execution.

Constant Summary

Constants inherited from Dry::Monads::Try

DEFAULT_EXCEPTIONS

Instance Attribute Summary

Attributes inherited from Dry::Monads::Try

#exception

Instance Method Summary collapse

Methods included from RightBiased::Left

#and, #apply, #bind, #deconstruct, #deconstruct_keys, #discard, #flatten, #fmap, #or_fmap, #tee, trace_caller, #value!, #value_or, #|

Methods inherited from Dry::Monads::Try

[], #error?, pure, run, #to_monad, #value?

Constructor Details

#initialize(exception) ⇒ Error

Returns a new instance of Error.

Parameters:

  • exception (Exception)


186
187
188
189
190
# File 'lib/dry/monads/try.rb', line 186

def initialize(exception)
  super()

  @exception = exception
end

Instance Method Details

#===(other) ⇒ Boolean

Parameters:

Returns:

  • (Boolean)


218
219
220
# File 'lib/dry/monads/try.rb', line 218

def ===(other)
  Error === other && exception === other.exception
end

#or(*args) ⇒ Object

If a block is given passes internal value to it and returns the result, otherwise simply returns the first argument.

Examples:

Try(ZeroDivisionError) { 1 / 0 }.or { "zero!" } # => "zero!"

Parameters:

  • args (Array<Object>)

    arguments that will be passed to a block if one was given, otherwise the first value will be returned

Returns:

  • (Object)


208
209
210
211
212
213
214
# File 'lib/dry/monads/try.rb', line 208

def or(*args)
  if block_given?
    yield(exception, *args)
  else
    args[0]
  end
end

#recover(*errors) ⇒ Try::Value

Acts in a similar way to rescue. It checks if Dry::Monads::Try#exception is one of errors and yields the block if so.

Parameters:

  • errors (Class)

    List of Exception subclasses

Returns:



228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/dry/monads/try.rb', line 228

def recover(*errors)
  if errors.empty?
    classes = DEFAULT_EXCEPTIONS
  else
    classes = errors
  end

  if classes.any? { _1 === exception }
    Value.new([exception.class], yield(exception))
  else
    self
  end
end

#to_maybeMaybe::None

Returns:



425
426
427
# File 'lib/dry/monads/maybe.rb', line 425

def to_maybe
  Maybe::None.new(RightBiased::Left.trace_caller)
end

#to_resultResult::Failure

Returns:



452
453
454
# File 'lib/dry/monads/result.rb', line 452

def to_result
  Result::Failure.new(exception, RightBiased::Left.trace_caller)
end

#to_sString Also known as: inspect

Returns:

  • (String)


193
194
195
# File 'lib/dry/monads/try.rb', line 193

def to_s
  "Try::Error(#{exception.class}: #{exception.message})"
end