Options
All
  • Public
  • Public/Protected
  • All
Menu

The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the Either type.

Try is a sum type and so instances of Try are either instances of Success or of Failure.

For example, Try can be used to perform division on a user-defined input, without the need to do explicit exception-handling in all of the places that an exception might occur.

Example:

function divide(dividendS: string, divisorS: string): string {
  const dividend = Try(() => parseInt(dividendS))
    .filter(_ => _ === _) // filter out NaN
  const divisor = Try(() => parseInt(divisorS))
    .filter(_ => _ === _)  // filter out NaN

  // map2 executes the given function only if both results are
  // successful; we could also express this with flatMap / chain
  const result = Try.map2(dividend, divisor,
    (a, b) => a / b
  )

  result.fold(
    error => `failure: ${error}`
    result => `result: ${result}`
  )
}

An important property of Try is its ability to pipeline, or chain, operations, catching exceptions along the way. The flatMap and map combinators each essentially pass off either their successfully completed value, wrapped in the Success type for it to be further operated upon by the next combinator in the chain, or the exception wrapped in the Failure type usually to be simply passed on down the chain. Combinators such as recover and recoverWith are designed to provide some type of global behavior in the case of failure.

NOTE: all Try combinators will catch exceptions and return failure unless otherwise specified in the documentation.

Type parameters

  • A

Hierarchy

Implements

Index

Constructors

Protected constructor

  • new Try(value: Throwable | A, tag: "failure" | "success"): Try

Properties

value

value: Throwable | A

Methods

ap

  • ap<B>(ff: Try<function>): Try<B>
  • Applicative apply operator.

    Resembles map, but the passed mapping function is lifted in the Either context.

    Type parameters

    • B

    Parameters

    • ff: Try<function>

    Returns Try<B>

chain

  • chain<B>(f: function): Try<B>

equals

  • equals(that: Try<A>): boolean

failed

filter

  • filter<B>(p: function): Try<B>
  • filter(p: function): Try<A>
  • Returns a Failure if the source is a Success, but the given p predicate is not satisfied.

    throws

    NoSuchElementError in case the predicate doesn't hold

    Type parameters

    • B: A

    Parameters

    • p: function
        • (a: A): boolean
        • Parameters

          • a: A

          Returns boolean

    Returns Try<B>

  • Parameters

    • p: function
        • (a: A): boolean
        • Parameters

          • a: A

          Returns boolean

    Returns Try<A>

flatMap

  • flatMap<B>(f: function): Try<B>
  • Returns the given function applied to the value if this is a Success or returns this if this is a Failure.

    This operation is the monadic "bind" operation. It can be used to chain multiple Try references.

    Try.of(() => parse(s1)).flatMap(num1 =>
      Try.of(() => parse(s2)).map(num2 =>
        num1 / num2
      ))
    

    Type parameters

    • B

    Parameters

    • f: function
        • (a: A): Try<B>
        • Parameters

          • a: A

          Returns Try<B>

    Returns Try<B>

fold

  • fold<R>(failure: function, success: function): R
  • Applies the failure function to Failure values, and the success function to Success values and returns the result.

    const maybeNum: Try<number> =
      tryParseInt("not a number")
    
    const result: string =
      maybeNum.fold(
        error => `Could not parse string: ${error}`,
        num => `Success: ${num}`
      )
    

    Type parameters

    • R

    Parameters

    • failure: function
    • success: function
        • (a: A): R
        • Parameters

          • a: A

          Returns R

    Returns R

forEach

  • forEach(cb: function): void
  • Applies the given function cb if this is a Success, otherwise returns void if this is a Failure.

    Parameters

    • cb: function
        • (a: A): void
        • Parameters

          • a: A

          Returns void

    Returns void

get

  • get(): A
  • Returns a Try's successful value if it's a Success reference, otherwise throws an exception if it's a Failure.

    WARNING!

    This function is partial, the option must be non-empty, otherwise a runtime exception will get thrown. Use with care.

    Returns A

getOrElse

  • getOrElse<AA>(fallback: AA): A | AA
  • Returns the value from a Success or the given fallback value if this is a Failure.

    Success(10).getOrElse(27) // 10
    Failure("error").getOrElse(27)  // 27
    

    Type parameters

    • AA

    Parameters

    • fallback: AA

    Returns A | AA

getOrElseL

  • getOrElseL<AA>(thunk: function): A | AA
  • Returns the value from a Success or the value generated by a given thunk in case this is a Failure.

    Success(10).getOrElseL(() => 27) // 10
    Failure("error").getOrElseL(() => 27)  // 27
    

    Type parameters

    • AA

    Parameters

    • thunk: function
        • (): AA
        • Returns AA

    Returns A | AA

hashCode

  • hashCode(): number

isFailure

  • isFailure(): boolean

isSuccess

  • isSuccess(): boolean

map

  • map<B>(f: function): Try<B>
  • Returns a Try containing the result of applying f to this option's value, but only if it's a Success, or returns the current Failure without any modifications.

    NOTE: this is similar with flatMap, except with map the result of f doesn't need to be wrapped in a Try.

    Type parameters

    • B

    Parameters

    • f: function

      the mapping function that will transform the value of this Try if successful.

        • (a: A): B
        • Parameters

          • a: A

          Returns B

    Returns Try<B>

    a new Try instance containing the value of the source mapped by the given function

orElse

  • orElse<AA>(fallback: Try<AA>): Try<A | AA>
  • Returns the current value if it's a Success, or if the source is a Failure then return the fallback.

    Success(10).orElse(Success(17))      // 10
    Failure("error").orElse(Success(17)) // 17
    

    Type parameters

    • AA

    Parameters

    • fallback: Try<AA>

    Returns Try<A | AA>

orElseL

  • orElseL<AA>(thunk: function): Try<A | AA>
  • Returns the current value if it's a Success, or if the source is a Failure then return the value generated by the given thunk.

    Success(10).orElseL(() => Success(17))      // 10
    Failure("error").orElseL(() => Success(17)) // 17
    

    Type parameters

    • AA

    Parameters

    • thunk: function

    Returns Try<A | AA>

orNull

  • orNull(): A | null
  • Returns the current value if it's a Success, or if the source is a Failure then return null.

    Success(10).orNull()      // 10
    Failure("error").orNull() // null
    

    This can be useful for use-cases such as:

    Try.of(() => dict.user.profile.name).orNull()
    

    Returns A | null

orUndefined

  • orUndefined(): A | undefined
  • Returns the current value if it's a Success, or if the source is a Failure then return undefined.

    Success(10).orUndefined()      // 10
    Failure("error").orUndefined() // undefined
    

    This can be useful for use-cases such as:

    Try.of(() => dict.user.profile.name).orUndefined()
    

    Returns A | undefined

recover

  • recover<AA>(f: function): Try<A | AA>
  • Applies the given function f if this is a Failure, otherwise returns this if this is a Success.

    This is like map for the exception.

    In the following example, if the user.profile.email exists, then it is returned as a successful value, otherwise

    Try.of(() => user.profile.email).recover(e => {
      // Access error? Default to empty.
      if (e instanceof TypeError) return ""
      throw e // We don't know what it is, rethrow
    })
    
    Note that on rethrow, the error is being caught in `recover` and
    it still returns it as a `Failure(e)`.
    

    Type parameters

    • AA

    Parameters

    Returns Try<A | AA>

recoverWith

  • recoverWith<AA>(f: function): Try<A | AA>
  • Applies the given function f if this is a Failure, otherwise returns this if this is a Success.

    This is like map for the exception.

    In the following example, if the user.profile.email exists, then it is returned as a successful value, otherwise

    Try.of(() => user.profile.email).recover(e => {
      // Access error? Default to empty.
      if (e instanceof TypeError) return ""
      throw e // We don't know what it is, rethrow
    })
    
    Note that on rethrow, the error is being caught in `recover` and
    it still returns it as a `Failure(e)`.
    

    Type parameters

    • AA

    Parameters

    Returns Try<A | AA>

toEither

  • Transforms the source into an Either.

    In case the source is a Success(v), then it gets translated into a Right(v). If the source is a Failure(e), then a Left(e) value is returned.

    Success("value").toEither() // Right("value")
    Failure("error").toEither() // Left("error")
    

    Returns Either<Throwable, A>

toOption

  • Transforms the source into an Option.

    In case the source is a Success(v), then it gets translated into a Some(v). If the source is a Failure(e), then a None value is returned.

    Success("value").toOption() // Some("value")
    Failure("error").toOption() // None
    

    Returns Option<A>

Static failure

Static map2

  • map2<A1, A2, R>(fa1: Try<A1>, fa2: Try<A2>, f: function): Try<R>
  • Maps 2 Try values by the mapping function, returning a new Try reference that is a Success only if both Try values are a Success, otherwise it returns the first Failure noticed.

    // Yields Success(3)
    Try.map2(Success(1), Success(2),
      (a, b) => a + b
    )
    
    // Yields Failure, because the second arg is a Failure
    Try.map2(Success(1), Failure("error"),
      (a, b) => a + b
    )
    

    This operation is the Applicative.map2.

    Type parameters

    • A1

    • A2

    • R

    Parameters

    • fa1: Try<A1>
    • fa2: Try<A2>
    • f: function
        • (a1: A1, a2: A2): R
        • Parameters

          • a1: A1
          • a2: A2

          Returns R

    Returns Try<R>

Static map3

  • map3<A1, A2, A3, R>(fa1: Try<A1>, fa2: Try<A2>, fa3: Try<A3>, f: function): Try<R>
  • Maps 3 Try values by the mapping function, returning a new Try reference that is a Success only if all 3 Try values are a Success, otherwise it returns the first Failure noticed.

    // Yields Success(6)
    Try.map3(Success(1), Success(2), Success(3),
      (a, b, c) => {
        return a + b + c
      }
    )
    
    // Yields Failure, because the second arg is a Failure
    Try.map3(
      Success(1),
      Failure("error"),
      Success(3),
    
      (a, b, c) => {
        return a + b + c
      }
    )
    

    Type parameters

    • A1

    • A2

    • A3

    • R

    Parameters

    • fa1: Try<A1>
    • fa2: Try<A2>
    • fa3: Try<A3>
    • f: function
        • (a1: A1, a2: A2, a3: A3): R
        • Parameters

          • a1: A1
          • a2: A2
          • a3: A3

          Returns R

    Returns Try<R>

Static map4

  • map4<A1, A2, A3, A4, R>(fa1: Try<A1>, fa2: Try<A2>, fa3: Try<A3>, fa4: Try<A4>, f: function): Try<R>
  • Maps 4 Try values by the mapping function, returning a new Try reference that is a Success only if all 4 Try values are a Success, otherwise it returns the first Failure noticed.

    // Yields Success(10)
    Try.map4(Success(1), Success(2), Success(3), Success(4),
      (a, b, c, d) => {
        return a + b + c + d
      }
    )
    
    // Yields Failure, because the second arg is a Failure
    Try.map3(
      Success(1),
      Failure("error"),
      Success(3),
      Success(4),
    
      (a, b, c, d) => {
        return a + b + c + d
      }
    )
    

    Type parameters

    • A1

    • A2

    • A3

    • A4

    • R

    Parameters

    • fa1: Try<A1>
    • fa2: Try<A2>
    • fa3: Try<A3>
    • fa4: Try<A4>
    • f: function
        • (a1: A1, a2: A2, a3: A3, a4: A4): R
        • Parameters

          • a1: A1
          • a2: A2
          • a3: A3
          • a4: A4

          Returns R

    Returns Try<R>

Static map5

  • map5<A1, A2, A3, A4, A5, R>(fa1: Try<A1>, fa2: Try<A2>, fa3: Try<A3>, fa4: Try<A4>, fa5: Try<A5>, f: function): Try<R>
  • Maps 5 Try values by the mapping function, returning a new Try reference that is a Success only if all 5 Try values are a Success, otherwise it returns the first Failure noticed.

    // Yields Success(15)
    Try.map5(
      Success(1),
      Success(2),
      Success(3),
      Success(4),
      Success(5),
    
      (a, b, c, d, e) => {
        return a + b + c + d + e
      }
    )
    
    // Yields Failure, because the second arg is a Failure
    Try.map5(
      Success(1),
      Failure("error"),
      Success(3),
      Success(4),
      Success(5),
    
      (a, b, c, d, e) => {
        return a + b + c + d + e
      }
    )
    

    Type parameters

    • A1

    • A2

    • A3

    • A4

    • A5

    • R

    Parameters

    • fa1: Try<A1>
    • fa2: Try<A2>
    • fa3: Try<A3>
    • fa4: Try<A4>
    • fa5: Try<A5>
    • f: function
        • (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): R
        • Parameters

          • a1: A1
          • a2: A2
          • a3: A3
          • a4: A4
          • a5: A5

          Returns R

    Returns Try<R>

Static map6

  • map6<A1, A2, A3, A4, A5, A6, R>(fa1: Try<A1>, fa2: Try<A2>, fa3: Try<A3>, fa4: Try<A4>, fa5: Try<A5>, fa6: Try<A6>, f: function): Try<R>
  • Maps 6 Try values by the mapping function, returning a new Try reference that is a Success only if all 6 Try values are a Success, otherwise it returns the first Failure noticed.

    // Yields Success(21)
    Try.map6(
      Success(1),
      Success(2),
      Success(3),
      Success(4),
      Success(5),
      Success(6),
    
      (a, b, c, d, e, f) => {
        return a + b + c + d + e + f
      }
    )
    
    // Yields Failure, because the second arg is a Failure
    Try.map6(
      Success(1),
      Failure("error"),
      Success(3),
      Success(4),
      Success(5),
      Success(6),
    
      (a, b, c, d, e, f) => {
        return a + b + c + d + e + f
      }
    )
    

    Type parameters

    • A1

    • A2

    • A3

    • A4

    • A5

    • A6

    • R

    Parameters

    • fa1: Try<A1>
    • fa2: Try<A2>
    • fa3: Try<A3>
    • fa4: Try<A4>
    • fa5: Try<A5>
    • fa6: Try<A6>
    • f: function
        • (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): R
        • Parameters

          • a1: A1
          • a2: A2
          • a3: A3
          • a4: A4
          • a5: A5
          • a6: A6

          Returns R

    Returns Try<R>

Static of

  • of<A>(thunk: function): Try<A>
  • Evaluates the given thunk and returns either a Success, in case the evaluation succeeded, or a Failure, in case an exception was thrown.

    Example:

    let effect = 0
    
    const e = Try.of(() => { effect += 1; return effect })
    e.get() // 1
    

    Type parameters

    • A

    Parameters

    • thunk: function
        • (): A
        • Returns A

    Returns Try<A>

Static pure

  • pure<A>(value: A): Try<A>

Static raise

Static success

  • success<A>(value: A): Try<A>
  • Returns a Try reference that represents a successful result (i.e. wrapped in Success).

    Type parameters

    • A

    Parameters

    • value: A

    Returns Try<A>

Static tailRecM

  • tailRecM<A, B>(a: A, f: function): Try<B>

Static unit

  • unit(): Try<void>
  • Shorthand for now(undefined as void), always returning the same reference as optimization.

    Returns Try<void>

Legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated using TypeDoc