basickarl
basickarl

Reputation: 40484

Export module and throwing errors/stopping execution on import

I have a database module. I'd like the module to do a check when it is being imported for the first time and crash if the database module cannot make a connection to the database. Fail fast, fail hard.

For this example we will be using knex, but the question is really for any module or any situation.

database.js file:

'use strict';
import knex from 'knex';

const instance = knex({
  client: 'mysql',
  connection: {
    database: 'myDatabase',
    host: 'host_that_does_not_exist',
    password: '',
    port: 3306,
    user: 'bob'
  }
});

instance.raw('select 1+1 as result').catch(err => {
  throw new Error('Database connection was not found', err);
});

export default instance;

As you see, I'd like for it to test a raw query and it is catches an error, throw an error.

I only know of one way of stopping node, and that is to call process.exit(1).

Is this the only way of doing this?

Upvotes: 2

Views: 84

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074505

Since you won't know the result until the completion of an asynchronous process, you can't actually throw an error during import. It would be later.

At that point, if you wanted to forcibly terminate Node, then yes, process.exit would do it. But I'd strongly recommend not terminating the process from within a module. The process isn't owned by the module.

Instead, I'd have the module return a promise which is either resolved with your instance, or rejected with an error. That ensures that things remain under the caller's control while forcing them to handle the asynchronous nature of your module init.

Something vaguely like this:

'use strict';
import knex from 'knex';

const instance = knex({
  client: 'mysql',
  connection: {
    database: 'myDatabase',
    host: 'host_that_does_not_exist',
    password: '',
    port: 3306,
    user: 'bob'
  }
});

const modulePromise = instance.raw('select 1+1 as result')
    .then(() => instance)
    .catch(err => {
      throw new Error('Database connection was not found', err);
    });

export default modulePromise;

...which caller would use like this:

import niftyModulePromise from "./your-module";
niftyModulePromise
    .then(module => {
        // Use it
    })
    .catch(err => {
        // Handle it -- process exit if desired
    });

Upvotes: 1

Related Questions