【发布时间】:2017-11-20 14:12:21
【问题描述】:
我开发了自定义通用指令,它将提供给定类型的参数(如果存在),否则拒绝我的自定义异常。
import akka.http.scaladsl.common.NameReceptacle
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.ParameterDirectives.ParamDefAux
import akka.http.scaladsl.server.{Directive1, Route}
class MyCustomException(msg: String) extends Exception(msg)
def requireParam[T](name: NameReceptacle[T])
(implicit pdef: ParamDefAux[NameReceptacle[T], Directive1[T]]): Directive1[T] =
parameter(name).recover { _ =>
throw new MyCustomException(s"${name.name} is missed!")
}
如果我想创建路由,可以使用两个参数,例如:
val negSumParams: Route =
(requireParam("param1".as[Int]) & requireParam("param2".as[Int])) {
(param1, param2) =>
complete((-param1-param2).toString)
}
但如果我尝试只使用一个参数,则无法编译:
val negParamCompilationFail: Route =
requireParam("param".as[Int]) {
param => // scalac complains about missing type param here
complete((-param).toString)
}
如果我将它与pass 指令一起使用,它可以工作:
val negParamWithPass: Route =
(pass & requireParam("param".as[Int])) { // this pass usage looks hacky
param =>
complete((-param).toString)
}
如果我明确写出requireParam() 返回类型,它也可以:
val negParamWithExplicitType: Route =
(requireParam("param".as[Int]): Directive1[Int]) { // DRY violation
param =>
complete((-param).toString)
}
为什么我需要这些技巧?为什么不能只使用requireParam("param".as[Int])?
Scala 版本 2.12.1,Akka-HTTP 10.0.10。
【问题讨论】: