承诺失败时如何捕捉?

问题描述 投票:1回答:2

Problem

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

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

Code

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
2个回答
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?
   });

1
投票

如果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");
}
© www.soinside.com 2019 - 2024. All rights reserved.