我在Scala上有一个电报机器人,如果它存在,我想发送图像给用户,如果它不存在,我想发送消息“对不起,图像不存在”。我有一个函数getImage(tag),它返回Future.successful(link)或Future.failed(NoImageException(msg))。
onCommand("/img") { implicit msg =>
val tag = msg.text.get.drop("/img ".length)
try {
if (tag.isEmpty) throw new IndexOutOfBoundsException()
service.getImage(tag).transform {
case Success(link) => Success(
try {
replyWithPhoto(InputFile(link))
} catch {
case _ => reply(link) // maybe it isn't a photo...
})
case Failure(e) => Success(reply(e.getMessage))
}.void
} catch {
case _: IndexOutOfBoundsException => reply("Empty argument list. Usage: /img tag").void
}}如果成功,此代码将发送一个图像,但如果失败,则不会发送消息(但在本例中,它肯定选择case Failure(e) )
发布于 2020-03-30 02:35:59
reply系列函数返回一个Future[Message]。目前您将reply的结果包装在Success中,因此您的transform的结果是Future[Future[Message]],这是不起作用的。相反,您可以使用transformWith,它的参数应为Future结果:
onCommand("/img") { implicit msg =>
val tag = msg.text.get.drop("/img ".length)
val message: Future[Message] =
if (tag.isEmpty) reply("Empty argument list. Usage: /img tag")
else {
service.getImage(tag).transformWith {
case Success(link) => replyWithPhoto(InputFile(link)).recoverWith {
case _ => reply(link) // maybe it isn't a photo...
}
case Failure(e) => reply(e.getMessage)
}
}
message.void
}请注意,我还删除了这两个try操作符。外部是不必要的,因为您可以只使用if/else。内部函数根本不起作用,因为replyWithPhoto返回一个Future。所以它不会抛出错误,当它失败时,你需要使用recover或transform。
https://stackoverflow.com/questions/60914673
复制相似问题