try-catch-finally.js
Installation
Browser
console // -> functionconsole // -> function
AMD
;
Node
npm install --save try-catch-finally
var _try = ;console; // -> function
Usage
API
_try ( tryBlock )
- tryBlock
<function>
- code which may throw errors
.catch ( [ error, ] handleError )
- error
<any>
- (optional) error to catch - handleError
<function>
- handle errors which correspond to error (if defined); else handle any error
.finally ( finallyBlock )
- finallyBlock
<function>
- code which will always exectue
Examples
Catch anything
;
Error value matches by strict equality (===
).
Catch-by-value
;
Error value matches by strict equality (===
).
Catch-by-name
;
Error name matches similarly to typeof
, with the bonus that it:
- is case-insensitive
- works for boxed primitives (e.g.
new String()
)
Catch-by-type
; ;
Error type matches similarly to instanceof
, with the bonus that it works for literal primitives ('hello'
, 123
, etc).
Warnings
Catch-by-name may not work
It's not always possible to get the name of an object in JavaScript, such as for objects created using non-native constructors:
{} ;
Or for some native objects which use inheritance:
;
Those catch blocks won't execute. The best this library can do is find out that:
- the
new CustomError()
is some kind ofobject
, but not specifically aCustomError
by name - the
new TypeError()
is some kind ofError
, but not specifically aTypeError
by name
It's best to use the catch-by-type style in those cases.
Catch-by-type won't work across frames/processes
This quirk exists in the native instanceof
, which fails across browser frames and node processes when the instance's constructor is different one passed to instanceof
. It's best to use the catch-by-name in those cases.
Errors are consumed
Any error thrown synchronously in the try block is consumed by this library. There are two ways to ensure errors which aren't caught/handled by any catch
don't disappear:
Use an indiscriminate catch block
;
Use a finally block
This will cause any unhandled error to be re-thrown:
;