在下面的代码片段中,我有一个递归函数调用,用于在网络调用失败时促进重试(Amazon SimpleDB偶尔会返回503并需要重试.)
当我尝试编译时,Scala抱怨道recursive method simpledb_update needs result type.
// sends data to SimpleDB. Retries if necessary
def simpledb_update(name: String, metadata: Map[String,String], attempt: Int) = {
try {
db(config("simpledb_db")) += (name, metadata)
} catch {
case e =>
// if it fails, try again up to 5 times
if(attempt < 6)
{
Thread.sleep(500)
simpledb_update(name, metadata, attempt + 1)
} else
AUlog(name + ": SimpleDB Failed")
}
}
Run Code Online (Sandbox Code Playgroud)
为什么递归函数需要这个?我的想法是只返回一个true/false布尔值来满足编译器...以下编译很好.
// sends data to SimpleDB. Retries if necessary
def simpledb_update(name: String, …Run Code Online (Sandbox Code Playgroud) 参考:
Scala 在scala控制器中返回关键字
处理错误
EDIT3
这是"最终"解决方案,再次感谢Dan Burton.
def save = Action { implicit request =>
val(orderNum, ip) = (generateOrderNum, request.remoteAddress)
val result = for {
model <- bindForm(form).right // error condition already json'd
transID <- payment.process(model, orderNum) project json
userID <- dao.create(model, ip, orderNum, transID) project json
} yield (userID, transID)
}
Run Code Online (Sandbox Code Playgroud)
然后是pimp'd Either项目方法,放在你的应用程序的某个地方(在我的例子中,一个impbits特性,sbt root和子项目扩展了它们的基础包对象:
class EitherProvidesProjection[L1, R](e: Either[L1, R]) {
def project[L1, L2](f: L1 => L2) = e match {
case Left(l:L1) => Left(f(l)).right
case Right(r) => Right(r).right …Run Code Online (Sandbox Code Playgroud)