Search code examples
javascriptnode.jserror-handlingecmascript-6custom-error-handling

In ES6 Node.js, how do I make a class available everywhere?


In my ES6 Node.js application, I have a file with a bunch of custom error classes, i.e.

class FirstCustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "FirstCustomError";
  }
}

class SecondCustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "SecondCustomError";
  }
}

// ...

How can I make these classes available everywhere in the application? Ideally, I don't have to import them in every file I need them in, and I don't have to resort to throw new global.errors.FirstCustomError('error message').

That is, ideally, I can just do throw new FirstCustomError('error message').


Solution

  • You can indeed just put them on the global object:

    global.FirstCustomError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "FirstCustomError";
      }
    };
    
    global.SecondCustomError = class extends Error {
      constructor(message) {
        super(message);
        this.name = "SecondCustomError";
      }
    };
    

    You would need to ensure that this happens before any other module is using them, i.e. you'd put it in a module that is required once at the beginning of your main script. An even better (more reusable) approach would be to export them as normal from your errors module, and then do

    Object.assign(global, require('./errors.js'));
    

    in your main script to install all exports as globals.


    Disclaimer: Of course, this is a horrible practice! Don't do that! Just do explicitly import them everywhere you need them. It's a breeze with ES6 module syntax, and it makes everything much clearer. Also it is unlikely that you have so many custom errors in your application that are of truly cross-cutting concerns and not tied to specific functionality, in which case you shouldn't put them all in the same module anyway.