[英]Error handling in Scala with Futures
The following method uses a future
to send email and then catches any exception mail.send
might throw: 以下方法使用future
发送电子邮件,然后捕获任何异常mail.send
可能抛出:
sendEmail(from: String, recipients: Seq[String],
subject: String, body: (Option[Txt], Option[Html])) = Try {
import com.typesafe.plugin._
import scala.concurrent.future
import play.api.libs.concurrent.Execution.Implicits.defaultContext
val mail = use[MailerPlugin].email
mail.addFrom(from)
recipients.map(mail.addRecipient(_))
subject.map(mail.setSubject(subject)
future {
try {
mail.send(body._1.map(_.body).getOrElse(""), body._2.map(_.body).getOrElse(""))
} catch {
case NonFatal(e) => Logger.warn("[%s] error sending email".format(ClassName, subject), e)
}
}
}
The method above returns either Success
or Failure
– for example mail.addFrom
might throw an exception if the sender email is invalid. 上面的方法返回Success
或Failure
-例如,如果发件人电子邮件无效, mail.addFrom
可能会引发异常。 Having said that, is it correct the way I deal with possible exceptions thrown inside the future
block? 话虽如此,我处理future
块中可能出现的异常的方式是否正确?
You don't need try
in future
. 你不需要try
在future
。
val f = future {
mail.send(body._1.map(_.body).getOrElse(""), body._2.map(_.body).getOrElse(""))
}
f.onFailure{
case NonFatal(e) => Logger.warn("[%s] error sending email".format(ClassName, subject), e)
}
Future
could contain successful result or failure in Try
container. Future
可能在“ Try
容器中包含成功结果或失败。 You could get Try
in onComplete
method, or transform Failure
to Success
using recover
method. 你可以得到Try
中onComplete
方法,或转换Failure
到Success
使用recover
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.