[英]Produce an error with scala and spray
我尝试使用scala和spray-routing创建简单的CRUD应用程序。 我有以下路线:
override def receive = runRoute {
path("entities" / LongNumber) { id =>
get {
produce(instanceOf[MyEntity]) {
func => ctx => heavyLookupById(id, func)
}
}
}
我是根据官方文档http://spray.io/documentation/1.2.2/spray-routing/marshalling-directives/produce/编写的
MyEntity是以下内容(无关紧要):
case class MyEntity(text: String, id: Option[Long])
而且我有以下json-support对象
object MyJsonSupport extends DefaultJsonProtocol with SprayJsonSupport {
implicit val format = jsonFormat2(MyEntity)
}
“ heavyLookupById”函数包含一些繁重的阻塞计算(假设数据库查询或http请求),因此我不得不处理scala future:
def heavyLookupById(id: Long, func: MyEntity => Unit) = {
// ... heavy computations
future onSuccess { case x => func(x) }
}
但是,如果我的未来失败了,我该怎么办? 我想用错误的请求(400)或未找到的(404)HTTP错误进行响应,但是该怎么做呢? 如果我没有在“ heavyLookupById”内部调用“ func”-请求只是挂起-我相信默认情况下服务器超时(1分钟左右)将失败。
你有RequestContext的(CTX),所以你可以调用拒绝,failWith或可用的任何其他方法RequestContext
。
val route = path("entities" / LongNumber) { id =>
get {
produce(instanceOf[MyEntity]) {
func => ctx => heavyLookupById(id, func, ctx)
}
}
}
def heavyLookupById(id: Long, func: MyEntity => Unit, ctx: RequestContext) = {
// ... heavy computations
val future = Future.successful(MyEntity("Hello", Some(1)))
future.onComplete {
case Success(value) => func(value)
case Failure(ex) => ctx.failWith(ex)
}
}
我个人更喜欢handleWith而不是农产品,我觉得它更容易阅读。
同样,在失败时,spray只会返回500,您可以使用exceptionHandlers对其进行自定义。
def heavyLookupById(id: Long) = {
// ... heavy computations
Future.successful(MyEntity("Hello", Some(1)))
}
val route = path("entities" / LongNumber) { id =>
get {
handleWith(heavyLookupById)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.