2017-06-04 114 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