任何想法为什么下面的代码可以处理Success
没有任何问题,但当试图返回Failure
最终扔Exception
?无法从scala接收失败未来
异常线程 “main” au.com.ingdirect.splunk.Implicits.package $ LameExcuse:你好 在au.com.ingdirect.splunk.Implicits.package $ RichJob $$ anonfun $ asFuture $ 1.适用(包.scala:42) at au.com.ingdirect.splunk.Implicits.package $ RichJob $$ anonfun $ asFuture $ 1.apply(package.scala:36) at scala.concurrent.impl.Future $ PromiseCompletingRunnable.liftedTree1 $ 1( Future.scala:24)
这是我的代码:
/* --- Main.scala --- */
import test.Implicits._
val job = service.createJob("search immediatePayment", queryArgs)
Await.result(job, 10 seconds)
job.onComplete{
case Success(j) => println("Success!!")
case Failure(l: LameExcuse) => println("Why I never fall here?")
}
/* --- package.scala ---*/
package object Implicits {
implicit val executorService = Executors.newFixedThreadPool(4)
implicit val executionContext = ExecutionContext.fromExecutorService(executorService)
case class LameExcuse(msg: String) extends Exception(msg)
implicit class RichJob(val job: Job) {
def asFuture(): Future[Job] = {
// I promise i will return a completed Job
val p = Promise[Job]()
val fail = false
// ... and here i am
future {
while (!job.isDone()) {
Thread.sleep(1000)
}
if (fail)
p failure (new LameExcuse("Service unavailable")) //<-- This will print the stacktrace on the console, but it will not send a Failure
else
p success job //<-- This works fine
}
p.future
}
}
感谢
我没有看到代码的任何错误。你能解释stacktrace究竟在哪里抛出异常吗.. – Jatin
LameExcuse扩展异常,试图摆脱这一点。顺便说一句:'新'对于案例班来说毫无用处! –