首页 > 解决方案 > 如何在 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 }

标签: javascriptnode.js

解决方案


您的构造函数不接受对象,但您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);


推荐阅读