try_catch.js (1585B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isFunction = require( '@stdlib/assert/is-function' ); 24 25 26 // MAIN // 27 28 /** 29 * If a function does not throw, returns the function return value; otherwise, returns `y`. 30 * 31 * @param {Function} x - function to try invoking 32 * @param {*} y - value to return if a function throws 33 * @throws {TypeError} first argument must be a function 34 * @returns {*} either the return value of `x` or the provided argument `y` 35 * 36 * @example 37 * var randu = require( '@stdlib/random/base/randu' ); 38 * 39 * function x() { 40 * if ( randu() < 0.5 ) { 41 * throw new Error( 'beep' ); 42 * } 43 * return 1.0; 44 * } 45 * var z = trycatch( x, -1.0 ); 46 * // returns <number> 47 */ 48 function trycatch( x, y ) { 49 if ( !isFunction( x ) ) { 50 throw new TypeError( 'invalid argument. First argument must be a function. Value: `'+x+'`.' ); 51 } 52 try { 53 return x(); 54 } catch ( error ) { // eslint-disable-line no-unused-vars 55 return y; 56 } 57 } 58 59 60 // EXPORTS // 61 62 module.exports = trycatch;