2

我想在正文中发送带有 JSON 格式消息的 Http 错误响应。我在使用PredefinedToResponseMarshallers时遇到问题。

我在Akka 文档中看到了一个实现,但我尝试了类似的事情,但它引发了编译错误。

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

我刚刚开始使用 Akka Http,如果它很简单,请原谅我。

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

4

1 回答 1

1

to[HttpResponse]负条件法取Future[HttpResponse]。同时正面条件返回HttpResponse

尝试类似的东西(我假设承担verifyFuture[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
于 2017-06-04T19:08:11.523 回答