javascript - Discord.js - Erela.js - Lavalink | 检查 Lavalink 是否没有返回结果
问题描述
我正在尝试检测 Lavalink 是否真的没有找到匹配项,因为有时我无法找到我确定存在的歌曲的匹配项。这就是我获得搜索结果的方式:
const searchResults = await client.music.search(query, message.author);
现在,如果真的没有匹配项,我最多要检查 5 次,所以我首先需要知道是否没有匹配项。我不知道如何检查是否没有匹配项,我已经尝试过:
if (!searchResults)
if (searchResults == undefined)
if (searchResults == null)
并且console.log(searchResults)
在没有匹配项时不会将任何内容记录到控制台。
编辑:我知道我目前的解决方案不是最好的,我真的很想听听你的建议
let searchResults;
try {
searchResults = await client.music.search(query, message.author);
} catch (error1) {
try {
searchResults = await client.music.search(query, message.author);
} catch (error2) {
try {
searchResults = await client.music.search(query, message.author);
} catch (error3) {
try {
searchResults = await client.music.search(query, message.author);
} catch (error4) {
try {
searchResults = await client.music.search(query, message.author);
} catch (error5) {
const musicničnašel = new MessageEmbed()
.setTitle("** GLASBA **")
.setColor(0xFF1E24)
.setDescription(`**Nisem našel glasbe na podlagi iskalnega niza:** ${query}
**Če si prepričan, da je bila to napaka, poskusi še enkrat!**`)
.setThumbnail("https://cdn0.iconfinder.com/data/icons/interface-2-9/34/85-512.png")
.setFooter('Za izboljšavo pišite predloge na: Anej#0001');
return message.channel.send(musicničnašel).then(d_msg => {d_msg.delete({ timeout: 10000 })});
}
}
}
}
}
解决方案
您可以使用递归函数来摆脱嵌套块。
这是一个示例实现:
const MAX_NO_OF_TRIALS = 5;
async function search(client, query, author, trialNumber = 0) {
try {
// Do the actual search here like the following
const result = await client.music.search(query, author)
if (result.exception || !(result.tracks.length || result.playlist.tracks.length))
throw new Error("no result found")
return result
} catch (error) {
if (trialNumber < MAX_NO_OF_TRIALS) {
console.log(`trial #${trialNumber + 1}`)
return await search(client, query, author, ++trialNumber)
}
else
throw error
}
}
// then you can use it inside an async block like:
try {
let searchResults = await search(client, query, message.author)
// do stuff with searchResults
} catch (error) {
// Error persists after 5 (MAX_NO_OF_TRIALS) trials
console.log("cant handle it")
}
这里我们定义了一个自定义搜索函数,它接受“client”、“query”和“author”。所以我们必须这样做,await search(client, query, message.author)
而不是client.music.search(query, message.author)
.
自定义搜索函数将从trialNumber
= 0 开始并 MAX_NO_OF_TRIALS
为 5。如果出现错误,搜索将递归调用自身,除非trialNumber
超出MAX_NO_OF_TRIALS
. (您可以设置 MAX_NO_OF_TRIALS
任意数量的最大尝试次数来修改行为。
根据以下实现创建检查:SearchResult.ts implementation here
推荐阅读
- flutter - 即使应用程序关闭也显示通知
- pine-script - 这“不是函数”(Pine-Script)
- kubernetes - 如何使用 Ingress 访问 Kubernetes 中的多个服务?
- java - 如何通过将值作为参数传递来从 Java 中的链表中删除值
- php - UTF8 编码的消息在 php smpp 短信发送中损坏字符
- php - PHP 检查是否有方法链接或返回结果
- spacy - spacy 段落级别的实体链接
- sql-server - 如何将 datetimeoffset 表列返回到自定义集中?
- css - 如何在 Bootstrap v5 中使用 @use 而不是 @import 进行自定义
- java - 使用 RxJava Flowable - 如何根据事件的类型拆分发射