我在Spray应用程序中使用ask模式调用Actor,并将结果作为HTTP响应返回.我将演员的失败映射到自定义错误代码.
val authActor = context.actorOf(Props[AuthenticationActor])
callService((authActor ? TokenAuthenticationRequest(token)).mapTo[LoggedInUser]) { user =>
complete(StatusCodes.OK, user)
}
def callService[T](f: => Future[T])(cb: T => RequestContext => Unit) = {
onComplete(f) {
case Success(value: T) => cb(value)
case Failure(ex: ServiceException) => complete(ex.statusCode, ex.errorMessage)
case e => complete(StatusCodes.InternalServerError, "Unable to complete the request. Please try again later.")
//In reality this returns a custom error object.
}
}
Run Code Online (Sandbox Code Playgroud)
当authActor发送失败时,这可以正常工作,但如果authActor抛出异常,则在询问超时完成之前不会发生任何事情.例如:
override def receive: Receive = {
case _ => throw new ServiceException(ErrorCodes.AuthenticationFailed, "No valid session was found for …Run Code Online (Sandbox Code Playgroud)