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')
}
Features
Supporting sync/async functions
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], (error) => {
}).other((error) => {
}).finally(({ result, error }) => {
return result;
});
console.log(result);
Example 2
const result = $try(() => {
return [1, 2, 3];
}).catch(ReferenceError, () => {
}).catch([TypeError, SyntaxError], (error) => {
}).other((error) => {
}).finally(({ result, error }) => {
return result;
});
console.log(result);
Example 3
const result = $try(() => {
throw SyntaxError;
})
console.log(result);
Promises example
class AuthError extends Error {}
function proc(event: string) {
return $try(() => new Promise((resolve, reject) => {
switch (event) {
case 'resolve':
resolve('resolved')
break;
case 'reject':
reject('rejected')
break;
case 'syntax':
throw SyntaxError
case 'auth':
throw AuthError
case 'error':
throw 'error'
default:
throw 'other errors'
}
}).catch('error', () => {
}).catch([SyntaxError, AuthError], (error) => {
}).other((error) => {
}).finally(({ value, error }) => {
})
}
await proc('resolve')
await proc('reject')
await proc('syntax')
await proc('auth')
await proc('error')
await proc('other')