Package Exports
- @rogwilco/try
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@rogwilco/try) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Try
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
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.
}