Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using throw in a Javascript expression

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?

like image 792
Andres Riofrio Avatar asked Mar 03 '12 09:03

Andres Riofrio


People also ask

Can we use Throw in JavaScript?

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.

Why we use Throw in JavaScript?

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.

How do you throw an exception in JavaScript?

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.

Does throw exit the function JavaScript?

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.


1 Answers

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);
like image 113
KooiInc Avatar answered Sep 22 '22 22:09

KooiInc