Héctor Valls
Héctor Valls

Reputation: 26084

How can I set response status code when using `RoutingContext::json` method?

I have this code:

get("/signup").handler {
  // some logic
  it.response()
    .setStatusCode(409)
    .putHeader("content-type", "application/json; charset=utf-8")
    .end(jsonObjectOf(
      "error" to "EmailAlreadyInUse"
    ).toString())
}

In order to simplify it, I want to use RoutingContext::json method:

get("/signup").handler {
  // some logic
  it
    .setStatusCode(409) // Can't do this, setStatusCode method doesn't exist in RoutingContext
    .json(jsonObjectOf(
      "error" to "EmailAlreadyInUse"
    ))
}

However, as you see, when RoutingContext::json method is used, I can't set the response's status code.

Is there any way to do this? (Without using a custom extension function)

Upvotes: 0

Views: 162

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17731

You can use Kotlin apply for that:

it.apply {
    response().statusCode = 409
    json(jsonObjectOf("error" to "EmailAlreadyInUse"))
}

Upvotes: 2

Related Questions