Search code examples
scalasprayspray-json

How do you get response code when using Custom Object instead of Httpresponse


When I use

val pipeline: HttpRequest => Future[HttpResponse] = addHeader(.......) ~> sendReceive ~>       unmarshal[HttpResponse]        

then I can get the Status code as it an object of HttpResponse using

val futureResponse = pipeline(Post(url, body)) futureResponse.map(_.status)

However, when I use a custom unmarshaller as:

val pipeline: HttpRequest => Future[MyResponse] = addHeader(.......) ~> sendReceive ~>      unmarshal[MyResponse]

using

val myfutureResponse = pipeline(Post(url, body))
myutureResponse.map(_.status)

doesn't compile as it cannot find status. How do I get the status code here? I need to use a custom unmarshaller to be able to deserialize my json result.


Solution

  • Finally I found an answer based on your suggestion

    private def unmarshal[T: Unmarshaller](response: HttpResponse): T = {
    response.entity.as[T] match {
      case Right(value) => value
      case Left(error)  ⇒ throw new PipelineException(error.toString)
    }
    

    }

    I changed my pipeline method to be

    val pipeline: HttpRequest => HttpResponse = addHeader(.......) ~> sendReceive
    val searchResponse = pipeline(Post(urlwithpath, queryString)).map {
      response => response.status match {
        case StatusCodes.OK =>
          Some(unmarshal[MyResponse](response))
        case StatusCodes.NotFound => print(StatusCodes.NotFound)
       }
    }
    

    Now that I have got this out of the way, I will learn the API properly