我的代码在数据库中搜索记录,并在找不到现有条目时返回错误。它需要在解析之前检查请求是否为空,如果找不到记录则返回一个空数组,如果确实找到了,则返回[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];
});
如果您的承诺无法解决,您可以尝试使用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?
});
如果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");
}