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 marker toss."

Is there a way to throw an exception on the same line that we are comparing, is the value false or not?

+7
source share
5 answers

throw is an expression, not an expression, so you cannot use it as part of another expression. You have to break it:

 var setting = process.env.SETTING; if (!setting) throw new Error("please set the SETTING environmental variable"); 
+15
source

You can use 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 general, create a function to throw errors and use this:

 function throwErr(mssg){ throw new Error(mssg); } var setting = process.env.SETTING || throwErr("please set the SETTING environmental variable"); 
+9
source

throw has no return value. Therefore, you cannot use it like that. However, you can wrap the cast in a function. Then it will work. But it will be harder to find the source of the exception.

+1
source

I see that you are using nodejs.

I believe that the best way to check the input parameters is to approve. NodeJS has a built-in simple approval module: http://nodejs.org/api/assert.html

And use it, for example, as follows:

 var assert = require('assert'); // ... function myFunction (param) { assert(param, 'please pass param'); // ... } 

In a test environment, you can do this as follows:

 require('assert')(process.env.setting, 'please set the SETTING environmental variable'); 

Or:

 ;(function (a) { a(process.env.setting, 'please set the SETTING environmental variable'); a(process.env.port, 'please set the PORT environmental variable'); }(require('assert'))); 
+1
source
 const getenv = require('getenv'); const setting = getenv('SETTING'); 

If SETTING does not exist, you will receive:

 … getenv.js:14 throw new Error('GetEnv.Nonexistent: ' + varName + ' does not exist ' + ^ Error: GetEnv.Nonexistent: SETTING does not exist and no fallback value provided. 

By the way, my experience tells me that the default values ​​for environment variables are evil.

0
source

All Articles