如果未定义则抛出错误?

时间:2018-06-05 14:59:51

标签: javascript node.js

如果无法从data找到属性,是否有办法抛出错误。

问题是,它映射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); 
    });
}

4 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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")
    });
}

答案 2 :(得分:0)

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

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));

这样做的好处是它支持深层属性访问。

答案 3 :(得分:0)

首先你需要正确启动你的Promise,因为你没有解决它,我喜欢这样做:

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())
}

这样每次都会出现正确的错误,但我不想使用字符串名称来访问属性