NodeJS 未定义时抛出错误?

mpbci0fu  于 2023-01-04  发布在  Node.js
关注(0)|答案(4)|浏览(146)

如果无法从data中找到属性,是否有方法引发错误。
问题是,它Map的是undefined,而不是抛出错误。

const insertIntoTable = function(data) {
    return new Promise((resolve, reject) => {
        const entry = {
            Id: data.id,
            Method: data.Method,
            Status: data.PaymentStatus,
            InsertedAt: (new Date().getTime())
        }
    }).catch((error) => {
       console.log(error); 
    });
}
ttygqcqt

ttygqcqt1#

您可以通过将其与undefined进行比较来检查属性是否未定义。例如,如果要检查id属性,可以使用

if(data.id === undefined){
     throw new Error();
}
djmepvbi

djmepvbi2#

const insertIntoTable = function(data) {
return new Promise((resolve, reject) => {
    if(data.id){
      const entry = {
        Id: data.id,
        Method: data.Method,
        Status: data.PaymentStatus,
        InsertedAt: (new Date().getTime())
      }
      return resolve(entry);
    }
    return reject();

    })
    .then((data) => {
        // treat your entry data
    }) 
    .catch(() => {
       throw new Error("data is undefined")
    });
}
mbskvtky

mbskvtky3#

首先你需要正确地开始你的承诺,因为你不是解决它,我喜欢这样做:

const insertIntoTable = function(data) {
    return Promise.resolve()
    .then(() => {
        const entry = {
            Id: data.id,
            Method: data.Method,
            Status: data.PaymentStatus,
            InsertedAt: (new Date().getTime())
        }
        // Do something with entry
    })
    .catch((error) => {
       console.log(error); 
    });
}

这样你就可以在你的内部进行验证(而不是拒绝)
你可以创建一个验证函数来检查未定义的变量,如下所示:

const validate = property => {
    if (property === undefined) throw 'data missing required property'
    return property
}

像这样使用它:

const entry = {
    Id: validate(data.id),
    Method: validate(data.Method),
    Status: validate(data.PaymentStatus),
    InsertedAt: (new Date().getTime())
}

但是这样你总是会得到同样的错误,你可以改变它来显示基于属性名的错误:

const getAndValidate = (data, propertyName) => {
    const property = data[propertyName]
    if (property === undefined) throw 'data missing the required property' + propertyName
    return property 
}

像这样使用它:

const entry = {
    Id: getAndValidate(data, 'id'),
    Method: getAndValidate(data, 'Method'),
    Status: getAndValidate(data, 'PaymentStatus'),
    InsertedAt: (new Date().getTime())
}

这样每次都能得到正确的错误,但我不喜欢使用字符串名称访问属性

goucqfw6

goucqfw64#

一种方法是利用短路评估,并执行以下操作:

const insertIntoTable = function(data) {
  return new Promise((resolve, reject) => {
      const entry = {
        Id: data.id || reject("data.id is undefined"),
        Method: data.Method  || reject("data.Method is undefined"),
        Status: data.PaymentStatus  || reject("data.PaymentStatus is undefined"),
        InsertedAt: (new Date().getTime())
      }
      resolve(entry);
  }).catch((error) => {
    console.log(error);
  });
}

insertIntoTable({}).then(data => console.log(data));

然而,我发现这很难阅读,所以我目前正在寻找一个更好的替代品。

更新

我一直在使用代理编写一个函数,它提供了可选或默认行为,该函数为

function optional(obj, evalFunc, def) {

  // Our proxy handler
  const handler = {
    // Intercept all property access
    get: function(target, prop, receiver) {
      const res = Reflect.get(...arguments);

      // If our response is an object then wrap it in a proxy else just return
      return typeof res === "object" ? proxify(res) : res != null ? res : def;
    }
  };

  const proxify = target => {
    return new Proxy(target, handler);
  };

  // Call function with our proxified object
  return evalFunc(proxify(obj, handler));
}

在这里可以被应用为

const insertIntoTable = function(data) {
  return new Promise((resolve, reject) => {
      const entry = {
        Id: optional(data, t => t.Id, reject('Id is not present')),
        Method: optional(data, t => t.Method, reject('Method is not present')),
        Status: optional(data, t => t.PaymentStatus, reject('PaymentStatus is not present')),
        InsertedAt: (new Date().getTime())
      }
      resolve(entry);
  }).catch((error) => {
    console.log(error);
  });
}

insertIntoTable({}).then(data => console.log(data));

这样做的优点是它支持深度属性访问。

相关问题