How should I respond with different status codes to a GET request in Spray?

StackOverflow https://stackoverflow.com/questions/15744392

  •  31-03-2022
  •  | 
  •  

Frage

For POST and PUT requests I use the following syntax:

put {
  entity(as[CaseClass]) { entity =>
     returnsOption(entity).map(result => complete{(Created, result)})
       .getOrElse(complete{(NotFound, "I couldn't find the parent resource you're modifying")})
  }
}

Now for GET requests I'm trying to do the same, but I can't get it to work analogously to my PUT solution. What is a good way to do this with GET requests?

Update: I've got this working with the following hack:

(get & parameters('ignored.?)) {
  //TODO find a way to do this without ignored parameters
  (ingored:Option[String]) => {
     returnsOption().map(result => complete(result))
       .getOrElse(complete{(NotFound, "")})
  }
 }

I'd expect something similar to be possible with () => or ctx => , but that doesn't fly, because it gives trouble with marshalling:

... could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[(spray.http.StatusCodes.ClientError, String)]
    }).getOrElse(ctx.complete{(NotFound, "")})
                             ^

Could it be that this somehow relates to the fact that I'm using spray-json?

War es hilfreich?

Lösung 2

This code should work:

get {
  ctx =>  
     ctx.complete(returnsOption())
 }

If don't use ctx => at the start, your code might only be executed at route build time.

Here you can find some explanations: Understanding the DSL Structure

Andere Tipps

Use HttpResponse like this for example

complete{
  HttpResponse(StatusCodes.OK, HttpBody(ContentType(`text/html`), "test test: " + System.currentTimeMillis.toString))
}

Update: I've been using Spray for a while now. Turned out there is better way:

complete {
  StatusCodes.BandwidthLimitExceeded -> MyCustomObject("blah blah")
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top