Here is what I want to do:
var setting = process.env.SETTING || throw new Error("please set the SETTING environmental variable");
^^^^^
But the interpreter complains about "Syntax Error: Unexpected token throw".
Is there any way to throw an exception in the same line that we compare whether a value is falsey or not?
In JavaScript, the throw statement handles user-defined exceptions. For example, if a certain number is divided by 0, and if you need to consider Infinity as an exception, you can use the throw statement to handle that exception.
The throw statement allows you to create a custom error. Technically you can throw an exception (throw an error). If you use throw together with try and catch , you can control program flow and generate custom error messages.
Throwing a generic exception is almost as simple as it sounds. All it takes is to instantiate an exception object—with the first parameter of the Error constructor being the error message—and then… "throw" it.
Using throw to exit a function in javascript While try and catch are usually used for fetching data, it can also be used to exit a function.
You can make use of the functional nature of javascript:
var setting = process.env.SETTING ||
function(){
throw "please set the SETTING environmental variable";
}();
// es201x
var 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With