我已经为在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吗?
发布于 2020-05-17 14:55:41
您可以将其赋值给nodejs的global变量。
如下所示:
global.CTIError = CTIError;现在您可以在任何地方访问CTIError,如下所示:
new CTIError()不过,linter可能会告诉您CTIError没有声明。
https://stackoverflow.com/questions/61853632
复制相似问题