@rogwilco/try
TypeScript icon, indicating that this package has built-in type declarations

2.1.0 • Public • Published

Try

NPM Package Build Status Code Coverage

A lightweight module that enables typed catch blocks.

Requirements

Note: Please consider these caveats for ES5 and TypeScript 2.1 when using this library in an unsupported environment.

Install

$ npm install @rogwilco/try

Documentation

TypeDoc Documentation

Usage

Try can be used in two different styles depending on preference.

Chaining

The chaining API completely replaces the usage of native try/catch/finally blocks. Simply start a chain with Try(), providing a function for the try block, followed by similar invocations of Catch() for each type of error you want to handle, and an optinal Finally() block. All usages must include a trailing call to Done() to ensure your code is executed.

import Try from 'Try'

Try(() => {
  // This block will be executed until an error is thrown.
  throw new ReferenceError('Something went wrong!')
})
  .Catch(ReferenceError, e => {
    // This block is only invoked if a ReferenceError is thrown.
    console.error(`Reference Error: ${e.message}`)
  })
  .Catch(TypeError, e => {
    // This block is only invoked if a TypeError is thrown.
    console.error(`Type Error: ${e.message}`)
  })
  .Finally(() => {
    // This block is executed regardless of wheter any errors were caught.
  })
  .Done()

Native

The native approach preserves the use of native try/catch/finally blocks, and provides a Handle() function for use within the catch block. The Handle() function will manage the handling of different error types (and will automatically re-throw an unmatched error).

import { Handle } from 'Try'

try {
  // This block will be executed until an error is thrown.
  throw new ReferenceError('Something went wrong!')
} catch (e) {
  Handle(e, {
    // This block is only invoked if a ReferenceError is thrown.
    ReferenceError: e => {
      console.error(`Reference Error: ${e.message}`)
    },
    // This block is only invoked if a TypeError is thrown.
    TypeError: e => {
      console.error(`Type Error: ${e.message}`)
    },
  })
} finally {
  // This block is executed regardless of wheter any errors were caught.
}

Package Sidebar

Install

npm i @rogwilco/try

Weekly Downloads

1

Version

2.1.0

License

BSD-3-Clause

Unpacked Size

13.8 kB

Total Files

6

Last publish

Collaborators

  • rogwilco