sansSpoon
sansSpoon

Reputation: 2185

Nodejs returning from try...catch

I'm running the following from node 9.5:

const { lstatSync, readdirSync } = require('fs');
const { resolve } = require('path');

const isDirectory = source => lstatSync(source).isDirectory();
const getDirectories = source =>
  readdirSync(source).map(name => resolve(source, name)).filter(isDirectory);

try {   
    const apiRoutes = getDirectories(__dirname + '/api');

    if (apiRoutes.length === 0) {
        throw new Error('API root must contain directories');
    }

    console.log(apiRoutes);

    return apiRoutes;

} catch (e) {
    console.error(`${e.name}: ${e.message}`);
}


//Why don't these fire?
console.log(apiRoutes);
console.log('foo');

Assuming there are two directories in api, the first console.log(apiRoutes) in the try block logs:

[/basedir/api/dir1,/basedir/api/dir2]

However, I can't get anything after the try block to run. If I don't return apiRoutes in the try block I get an undefined error.

How do I return a value from the try block?

Why doesn't foo get logged?

Upvotes: 1

Views: 2946

Answers (2)

user4162732
user4162732

Reputation:

You may need to declare apiRoutes outside of the try/catch. Once the try/catch completes you lose scope of the variable.

Upvotes: 1

Alex
Alex

Reputation: 35407

The apiRoutes constant is scoped within the try block.

Refactor the code to either move the console.logs within the try block, or change to defining apiRoutes with let in the outer scope; and setting its value within the try block by calling getDirectories.


This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared (which makes sense, given that it can't be changed later).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

Upvotes: 3

Related Questions