Options
All
  • Public
  • Public/Protected
  • All
Menu

Try - v2.0.0

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

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.
}

Generated using TypeDoc