Typed error handling for calling functions

import { Attempt } from "@testingrequired/attempted";

let attempt: Attempt<number> = Attempt.of(fnMightThrow, ...fnArgs);

// Returns true if function didn't throw or returned a failed attempt
attempt.isSuccessful();

// Returns true if function throws or returned a failed attempt
attempt.isFailure();

// You can conditionally run functions on successful or failed attempts
attempt.ifSuccessful((value) => {});
attempt.ifFailure((error) => {});
attempt.ifElse(
(value) => {},
(error) => {}
);

// Map over successful attempts
// This will not run on a failed attempt
attempt = attempt.map((n) => n * 2);

// Assert over successful attempts
// Failed assertions will return a failed attempt
// This will not run on a failed attempt
attempt = attempt.assert(
(value) => value > 100,
(value) => `Value ${value} was less than 100`
);

// Returns value on successful attempts
// Throws on failed attempts
attempt.get();

// Returns error on failed attempts
// Throws on successful attempts
attempt.getError();

// Get value on successful attempts or a default value.
attempt.orElse(defaultValue);

// Get value or throw provided error
attempt.orThrow(new Error("Something went wrong"));
attempt.orThrow("Something went wrong");

// You can pass function to access a failed attempt's error
attempt.orThrow((error) => new Error(`Something went wrong: ${e}`));
attempt.orThrow((error) => `Something went wrong`);

It also works with async functions!

import { Attempt } from "@testingrequired/attempted";

// Await the attempt the same as you would await the function call
let attempt: Attempt<number> = await Attempt.of(asyncFnMightThrow, ...fnArgs);

// You can use async functions to map as well
attempt = await attempt.map(async (n) => n * 2);

// Returns the attempts value
attempt.get();

You can also wrap a function to be called later

const attemptFnMightThrow = Attempt.wrap(fnMightThrow);
const attempt: Attempt<number> = attemptFnMightThrow(...fnArgs);

Type Parameters

  • T

    The successful value type

Hierarchy

  • Attempt

Constructors

Properties

#error: unknown

Error when the attempt failed

#value: undefined | T

Value when the attempt was successful

Methods

  • Assert against a successful attempt's value

    Attempt.ofValue(123)
    .assert(value => value > 100, (value) => new Error("Number isn't greater than 100"))
    .get() // 123

    Attempt.ofValue(123)
    .assert(value => value < 100, (value) => new Error(`Number $(value) isn't less than 100`))
    .getError() // Error("Number 123 isn't less than 100")

    Attempt.ofError<number>("Something went wrong")
    .assert(value => value > 100, (value) => new Error("Number isn't greater than 100"))
    .getError() // Error("Something went wrong")

    Parameters

    • assertionFn: ((value) => boolean)

      Assertion function to run

        • (value): boolean
        • Parameters

          • value: T

          Returns boolean

    • errorFn: ((value) => unknown)

      Function that returns an error if the assertion fails

        • (value): unknown
        • Parameters

          • value: T

          Returns unknown

    Returns Attempt<T>

    Either success/failed attempt from the assertion or the failed attempt it was called on

  • Get value from successful attempt. Throws if failed attempt.

    Attempt.ofValue(123).get() // 123
    Attempt.ofError("...").get() // Throws

    Returns T

    Value from a success attempt

  • Get error from failed attempt. Throws if successful attempt.

    Attempt.ofError("...").getError() // "..."
    Attempt.ofError("...").getError() // Throws

    Returns unknown

    Error from a failed attempt

  • Run success or failure function based on attempt

    Attempt.ofValue(123)
    .ifElse(
    value => console.log(`It worked! ${value}`),
    error => console.log(`It failed! ${error}`)
    )

    Parameters

    • successFn: ((value) => any)

      Function to run on successful attempt

        • (value): any
        • Parameters

          • value: T

          Returns any

    • failureFn: ((error) => any)

      Function to run on failed attempt

        • (error): any
        • Parameters

          • error: unknown

          Returns any

    Returns void

  • Run function is attempt failed

    Attempt.ofError("...").ifFailure(error => {}) // Runs
    Attempt.ofValue(123).ifFailure(error => {}) // Doesn't run

    Parameters

    • fn: ((error) => any)

      Fucntion to run

        • (error): any
        • Parameters

          • error: unknown

          Returns any

    Returns void

  • Run function if attempt was successful

    Attempt.ofValue(123).ifSuccess(value => {}) // Runs
    Attempt.ofError("...").ifSuccess(value => {}) // Doesn't run

    Parameters

    • fn: ((value) => any)

      Function to run

        • (value): any
        • Parameters

          • value: T

          Returns any

    Returns void

  • Get if attempt failed

    Attempt.ofError("...").isFailure() // true
    Attempt.ofValue(123).isFailure() // false

    Returns boolean

    Boolean if attempt failed

  • Get if attempt was successful

    Attempt.ofValue(123).isSuccess() // true
    Attempt.ofError("...").isSuccess() // false

    Returns boolean

    Boolean if attempt was successful

  • Get value from successful attempt or a default value on a failed attempt

    Attempt.ofValue(123).orElse(456) // 123
    Attempt<number>.ofError("...").orElse(456) // 456

    Parameters

    • defaultValue: T

    Returns T

    Successful attempt value or default value

  • Get value from successful attempt or a throw error

    Attempt.ofValue(123).orThrow(456) // 123
    Attempt<number>.ofError("...").orThrow("Something went wrong") // Error("Something went wrong")

    You can also get the error from a failed attempt

    Attempt<number>.ofError("...").orThrow((e) => "Something went wrong: ${e}") // Error("Something went wrong: ...")
    

    Type Parameters

    • ErrorToThrow extends Error = Error

    Parameters

    • errorToThrow: string | ErrorToThrow | ((error) => string | ErrorToThrow)

    Returns T

    Successful attempt value

  • Create a failed attempt result from an error

    // Attempt<unknown>
    const failedAttemptWithError = Attempt.ofError(new Error("Something went wrong"));

    // Attempt<unknown>
    const failedAttemptWithString = Attempt.ofError("Something went wrong");

    Type Parameters

    • T = unknown

      Value type if attempt had succeeded

    • E = unknown

    Parameters

    • error: E

      Error for the failed attempt

    Returns E extends Attempt<U>
        ? Attempt<U>
        : Attempt<T>

    Attempt with failure error

  • Create a successful attempt from a value

    // Attempt<number>
    const attempt = Attempt.ofValue(123);

    Type Parameters

    • T

      Value for the successful attempt

    Parameters

    • value: T

      Value of successful attempt

    Returns T extends Attempt<any>
        ? T
        : Attempt<T>

    Attempt with a success value

Generated using TypeDoc