简体   繁体   中英

global modules in node.js

I have made a custom error class for throwing error in node.js. I want to use this class in my entire project. But the problem is wherever I need to use first I have to require in that file and then use this class which is quite tedious. Anyone any idea how to make it global so that all the modules can use it without requiring it in every file.

This is a custom error class file "cti_error.js"

'use strict';
class CTIError extends Error {
    constructor (status,message,details='') {
        super(message)
        this.name = status
        Error.captureStackTrace(this, this.constructor);
        this.status = status || 500;
        this.details = details?details:message;
        this.reason = message;
    }
}
module.exports = CTIError;

My project structure:-

my_project
|
|____utility
|       |
|       |____cti_error.js
|
|____routes
|      |
|      |_____product.js
|      |_____defects.js
|
|
|_____server.js

The solution what I know is to require the custom error class as below in every file where I want to throw an error:-

const cti_error = require('../../utility/cti_error.js');
throw new cti_error(403,"wrong details");

Any idea how to use cti_eror without requiring in every file?

You can assign it to nodejs's global variable.

Like this:

global.CTIError = CTIError;

Now you can access the CTIError anywhere as:

new CTIError()

Your linter might tell you that CTIError is not declared though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM