Using throw in a Javascript expression
You can make use of the functional nature of javascript:
var setting = process.env.SETTING || function(){ throw "please set the SETTING environmental variable"; }();// es201xvar setting = process.env.SETTING || (() => {throw `SETTING environmental variable not set`})();
or more generic create a function to throw errors and use that:
function throwErr(mssg){ throw new Error(mssg);}var setting = process.env.SETTING || throwErr("please set the SETTING environmental variable");
A snippet I use:
const throwIf = ( assertion = false, message = `An error occurred`, ErrorType = Error) => assertion && (() => { throw new ErrorType(message); })();throwIf(!window.SOMESETTING, `window.SOMESETTING not defined`, TypeError);
throw
is a statement, not an expression, so you cannot use it as part of another expression. You have to split it:
var setting = process.env.SETTING;if (!setting) throw new Error("please set the SETTING environmental variable");
There is a draft proposal to introduce throw expressions (similar to C# 7's throw expressions) to JavaScript/ECMAScript: