javascript - 如何在 node.js 中为对象创建异常
问题描述
我试图用一个对象在 Node.js 中抛出一个异常。但我不知道如何自定义返回类。
例子:
class BusinessError extends Error {
constructor(code, status, message) {
super(message);
this.code = code;
this.name = 'Error';
this.status = status;
}
}
const error = {
code: '001',
status: 500,
message: 'Error',
}
throw new BusinessError(error.code, error.status, error.message);
但是,其他属性不会出现在返回中。
前任:
{ "message": "TypeError: foo 不是函数" }
但是,我希望它是这样的
{ "message": "TypeError: foo is not a function", "code": 'X-100', "status": 500 }
解决方案
您的构造函数不接受对象,但您BusinessError
使用对象进行了实例化。您可以尝试像这样在类构造函数中解构对象
class BusinessError extends Error {
constructor({ code, status, message }) {
super(message);
this.name = 'BusinessError';
this.status = status;
}
}
const error = {
code: '001',
status: 500,
message: 'This is an Error',
}
throw new BusinessError(error);
推荐阅读
- r - 从R中的大矩阵或data.table中按索引提取单行的最快方法?
- javascript - 我做了一个javascript函数,现在我想缩短它,我该怎么做?
- ios - 尝试使用闭包在 ViewController 之间传递数据时出现什么错误?
- sql - 在 SQL 中将 Str 格式的日期更改为 Datetime 格式
- java - 邮递员状态:访问 POST 请求 Web 服务时出现 415 不支持的媒体类型
- python - 将带有 GMT 的时间戳转换为 Pandas 中的时间戳
- android - 通过 ADB 检索 Android 呼叫日志
- gruntjs - 如何使用 Grunt 将文件复制到每个目录?
- python-3.x - 在 django 中将 html 转换为 pdf 时处理 base64 图像的对齐
- android - 如何在Android中计算两个TIMESTAMP之间的时间差