【问题标题】:How to catch when a promise fails?当一个承诺失败时如何捕捉?
【发布时间】:2019-08-20 21:31:01
【问题描述】:

问题

我的代码正在数据库中搜索记录并在找不到现有条目时返回错误。它需要在解析之前检查请求是否为空,如果没有找到记录则返回一个空数组,如果找到则返回[results]数组。我该如何解决这个问题?

这是用于 Zapier 与 Zoho CRM 的集成,它将通过 Account_Name 搜索自定义模块以查找现有记录,如果不存在则创建一个。

代码

const options = {
  url: `https://www.zohoapis.com/crm/v2/Accounts/search?criteria=(Account_Name:equals:${bundle.inputData.Account_Name})`,
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Zoho-oauthtoken ${bundle.authData.access_token}`,
    'Accept': 'application/json'
  },
  params: {

  }
}

return z.request(options)
  .then((response) => {
    response.throwForStatus();
    const results = [z.JSON.parse(response.content)];
    return [results];
  });

【问题讨论】:

    标签: javascript arrays json error-handling zapier


    【解决方案1】:

    如果您的承诺无法解决,您可以尝试使用catch

    喜欢:

    return z.request(options)
      .then((response) => {
        response.throwForStatus();
        const results = [z.JSON.parse(response.content)];
        return [results];
      })
      .catch(err => {
         /* 
          check if the error is specifically where no entry in db was found.
           Or if the error is always for that purpose
         */
         console.log(err) // handle error approriately, maybe send to sentry?
         return []; //emtpy array, when db errors out?
       });
    

    【讨论】:

    • 非常感谢 omkar!您的解决方案是正确的!几天来,我一直在努力使代码正确。我应该在不久前发布这个问题! catch 完美地返回了允许其余代码创建记录所需的空数组。非常感谢您的帮助!
    【解决方案2】:

    如果 response.content 未找到任何内容时为 null:

    .then((response) => {
       ...
       return (response.content) ? 
       [z.JSON.parse(response.content)] : 
       Error("invalid request");
    }
    

    如果 response.content 没有找到任何东西时是一个空对象:

    .then((response) => {
      ...
      return (Object.keys(response.content).length) ? 
      [z.JSON.parse(response.content)] 
      : Error("invalid request");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 2016-10-05
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      相关资源
      最近更新 更多