0.0.1 • Published 3 years ago

error-utilities v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

Description

Utility functions for error handling.

Installation

    $ npm install error-utilities

Usage

import {ignoreError, switchCatch, tryCatch, caseError} from "error-handling";

// Returns the result of invocation. 
// If error has been thrown, returns undefined.
const result = ignoreError(() => someFunctionThatMayThrow());
// Or default value
const result2 = ignoreError(() => someFunctionThatMayThrow(), 42);


class Error1 extends Error { ... }
class Error2 extends Error { ... }

try {
    const value = functionThatThrowsSeveralErrors();
} catch (error) {
    // If catched error is hanlded by one of cases, its corresponding handler
    // will be called. If error is not handled by switchCatch it will be
    // thrown again
    const result = switchCatch(error,
        caseError(Error1, (e: Error1) => 20),
        caseError(Error2, (e: Error2) => 20),
    );
}

// Same as above but wraps the invocation with try/catch automatically
const value = tryCatch(() => functionThatThrowsSeveralErrors(),
    caseError(Error1, (e: Error1) => 20),
    caseError(Error2, (e: Error2) => 20),
);