我做了一个自定义的错误类,用于在node.js中抛出错误。我想在我的整个项目中使用这个类。但问题是,无论我在哪里需要使用,首先我必须在该文件中要求,然后使用这个类,这是相当繁琐的。有谁知道如何使它成为全局的,使所有的模块都可以使用它,而不需要在每个文件中要求它。
这是一个自定义的错误类文件 "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
|
|____utility
| |
| |____cti_error.js
|
|____routes
| |
| |_____product.js
| |_____defects.js
|
|
|_____server.js
我所知道的解决方案是在每一个我想抛出错误的文件中都需要自定义错误类,如下图所示:-。
const cti_error = require('../../utility/cti_error.js');
throw new cti_error(403,"wrong details");
有什么办法可以不用在每个文件中都要求使用cti_eror?
你可以将它分配到nodejs的 global
变量。
像这样。
global.CTIError = CTIError;
现在你可以访问 CTIError
任何地方作为。
new CTIError()
你的雕刻师可能会告诉你 CTIError
虽然没有声明。