Tryor

tryor

try or return default.

tryor will give you back the return value of the function or, in case the function threw an exception, the default value.

tryor just wrap the fn and default in try-catch as below:

1
2
3
4
5
6
7
8
9
function tryor(fn, v) {
    "use strict";

    try {
        return fn();
    } catch (e) {
        return v;
    }
};

Get it: npm install tryor

Sample usage:

1
2
3
4
5
6
7
// instead of
let config;
try {
    config = JSON.parse(mayBeString);
} catch (e) {
    config = {};
}
1
2
// do this
const config = tryor(() => JSON.parse(mayBeString), {});

GIF FTW!

tryor

Suggest a module

Comments