Function wrapInTry

Calls the callback and returns its output. If the callback throws an error, it is handled in the following ways:

  • If a handleError function is provided in options, it is passed the thrown error. The output of handleError is returned by wrapInTry.
  • If a fallbackValue is provided, it is returned by wrapInTry. The thrown error is ignored.
  • If no options are provided, the thrown error is returned by wrapInTry.
import {wrapInTry} from '@augment-vir/common';

// `result1` will be `'success'`.
const result1 = wrapInTry(
() => {
return 'success';
},
{
fallbackValue: 'failure',
},
);
// `result2` will be `'failure'`.
const result2 = wrapInTry(
() => {
throw new Error();
return 'success';
},
{
fallbackValue: 'failure',
},
);
// `result3` will be `'failure also'`.
const result3 = wrapInTry(
() => {
throw new Error();
return 'success';
},
{
handleError() {
return 'failure also';
},
},
);
// `result4` will be `'failure also'`.
const result4 = wrapInTry(
() => {
throw new Error();
return 'success';
},
{
handleError() {
return 'failure also';
},
fallbackValue: 'ignored',
},
);