2017-06-04 32 views
1

我想發送一個帶有JSON格式正文消息的Http錯誤響應。我無法使用PredefinedToResponseMarshallers在Akka Http使用marshallers發送帶有Json內容的http響應

我在Akka docs看到了一個實現,但我嘗試了類似的東西,它會引發編譯錯誤。

import argonaut._, Argonaut._ 
import akka.http.scaladsl.marshalling.Marshal 
import akka.http.scaladsl.server.Directives._ 
import akka.http.scaladsl.model.HttpResponse 
import akka.http.scaladsl.model.headers._ 
import akka.http.scaladsl.model.StatusCodes._ 
import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshaller } 

trait Sample extends Marshallers with Directives { 
    def login(user: Login): CRIX[HttpResponse] = { 
     for { 
      verification ← verify(user) 
      resp = if (verification) { 
      HttpResponse(NoContent, headers = Seq(
       ......... 
      )) 
      }//below is my http Error response 
      else Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse] 
     } yield resp 
     } 
    } 

它給出了這樣的編譯錯誤:

Sample.scala:164: type mismatch; 
[error] found : Object 
[error] required: akka.http.scaladsl.model.HttpResponse 
[error]  } yield resp 
[error]   ^
[error] one error found 
[error] (http/compile:compileIncremental) Compilation failed 

我剛開始阿卡的Http所以原諒我,如果是簡單的。

TL; DR:我想(示例)瞭解如何在Akka Http中使用ToResponseMarshallers。

回答

1

負面情況的方法to[HttpResponse]承擔Future[HttpResponse]。同時積極條件返回HttpResponse

嘗試像(我假設verify呈現Future[T]):

for { 
    verification <- verify(user) 
    resp <- if (verification) 
      Future.successful(HttpResponse(NoContent, headers = Seq(.........))) 
     else 
      Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse] 
} yield resp 
+0

感謝,它爲我工作。 – Sudhanshu