catch-match

Motivation
java
try {
...
} catch (ExceptionClass1 e) {
....
} catch (ExceptionClass2, ExceptionClass3 e) {
....
} catch (any) {
...
} finally {
....
}
javascript
try {
error;
} catch (err) {
switch(err.constructor) {
case ReferenceError:
case SyntaxError:
console.error(`${err.constructor.name}: ${err.message}`);
break;
default:
console.error('other error:', err);
}
} finally {
console.log('final')
}
Getting started
yarn add catch-match
or
npm install catch-match
import $try from 'catch-match';
import { $try } from 'catch-match';
Example 1
const result = $try(() => {
throw SyntaxError;
}).catch(ReferenceError, () => {
}).catch([TypeError, SyntaxError], () => {
}).other((error) => {
}).finally(({ result, error }) => {
return result;
});
console.log(result);
Example 2
const result = $try(() => {
return [1, 2, 3];
}).catch(ReferenceError, () => {
}).catch([TypeError, SyntaxError], () => {
}).other((error) => {
}).finally(({ result, error }) => {
return result;
});
console.log(result);
Example 3
const result = $try(context => {
context.tmp = 'any context data';
console.log('start', context);
throw SyntaxError;
}).catch([TypeError, ReferenceError], (context) => {
}).other((error, context) => {
context.unexpectedError = true;
}).finally(({value, context, error}) => {
if (!error) {
return value.reverse();
}
});
console.log(result);