Akka Streams拆分流以进行错误处理

jvlzgdj9  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(165)

我使用akka http和streams来完成API请求。当请求无效时,我希望返回一个400,如果请求有效,我希望继续计算,并在之后返回结果。我面临的问题是,我从POST请求接收的有效负载是一个源,我无法将其转换为2个流(一个用于有效输入数据,一个用于无效输入数据),并正确完成请求。

path("alarms")(
  post(entity(asSourceOf[String]) { message =>
    val flow = message.via(Flow[String].map((it) => 
         Try(if valid(it) then it else throw Exception("Wrong input"))
    ))
    complete(repository.create(flow).run) // <-- here I only want to pass all events that are valid. For the other events complete(HttpResponse(NotFound, entity = "Invalid input")) should be used
  })
)
/// The signature of the repository.create looks like that
def create(message: Source[String, NotUsed]): RunnableGraph[Future[Done]]
dvtswwa3

dvtswwa31#

您可以使用akka-http handleExceptions指令,类似于以下内容:

val exceptionHandler = ExceptionHandler {
 case ex: RuntimeException =>
   complete(HttpResponse(NotFound, entity = "Invalid input"))
}

path("alarms")(
  handleExceptions(exceptionHandler) {
    post(entity(asSourceOf[String]) { message =>
      val flow = message.via(Flow[String].map((it) =>
        Try(if valid(it) then it else throw new RuntimeException("Invalid input"))
      ))
      complete(repository.create(flow).run)
  })
  }
)

文件名:
https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/execution-directives/handleExceptions.html
https://doc.akka.io/docs/akka-http/current/routing-dsl/exception-handling.html
还有handleRejections指令,用于更多控制-请参见https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/execution-directives/handleRejections.html

相关问题