简体   繁体   English

使用期货在Scala中进行错误处理

[英]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. 上面的方法返回SuccessFailure -例如,如果发件人电子邮件无效, 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 . 你不需要tryfuture

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. 你可以得到TryonComplete方法,或转换FailureSuccess使用recover方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM