How to change HTTP status code of AsyncResult using Scalatra

1k views Asked by At

I have created a simple controller (the code below is obfuscated and simplified, assume ask returns a future with a message). What I am trying to do is change the HTTP code from something other than 200 (based on the actor result).

When executing the code below I see the result come back as expected, but with 200 instead of 404

   get("/:id") {
        new AsyncResult() {
          val is: Future[_] = ask(actor, message)(timeout.toMillis)
          is.onComplete { res =>
            res match {
              case Success(result:Any) => NotFound(result) //Not found is just an example of a different HTTP code other than 200
          }
       }
    }

another attempt was

case Success(result:Any) => {
   this.status_ = (404)
   result
}

In this case, I receive a NullPointerException because the response (HTTPServletResponse) is null, due to the fact that the response is on a separate thread.

TL;DR

How can one conditionally change the HTTP code of an AsyncResult/Future in Scalatra?

Details

Scala 2.11.6

Scalatra 2.3.0

Akka 2.3.9

2

There are 2 answers

1
marteljn On BEST ANSWER

After some digging in the Scalatra FutureSupport mixin, I found:

implicit val response: HttpServletResponse = scalatraContext.response

defined as a member of AsyncResult which allows me change the status code of the HTTP request inside the onComplete callback.

0
Wins On

You actually can return Future[ActionResult] to is if you want. Then inside the Future you can return Ok()