我正在使用 akka http 和流來滿足 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]]
uj5u.com熱心網友回復:
你可以使用 akka-httphandleExceptions指令,像這樣:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403046.html
標籤:
