Vannak Noun
Vannak Noun

Reputation: 21

i want to putHeader to my url when timeout equal 5s but it error "java.lang.IllegalStateException: Response has already been written"

I want to redirect to another url when timeout equal 5s.

Code that I have:

private void timeout(RoutingContext handler) {
    vertx.setPeriodic(5000, new Handler<Long>() {
        @Override
        public void handle(Long aLong) {
            System.out.println("Session expired : " + aLong);       
            handler.response().putHeader("location","/logout").setStatusCode(302).end();
        }
    });
}

Error that I get is:

java.lang.IllegalStateException: Response has already been written"

Upvotes: 2

Views: 167

Answers (2)

cy3er
cy3er

Reputation: 1699

You need a simple timer not a periodic one:

private void timeout(RoutingContext ctx) {
    long tid = ctx.vertx().setTimer(5000, t -> {
        ctx.response().putHeader("location","/logout").setStatusCode(302).end();
    });
    ctx.addBodyEndHandler(v -> ctx.vertx().cancelTimer(tid));
}

and don't forget to cancel the timer in case there wasn't timeout!

Upvotes: 0

wero
wero

Reputation: 32980

You can't change a header when the response has already been written. But you could check this condition and write:

public void handle(Long aLong) {
    if (!handler.response().headWritten()) 
        handler.response().putHeader("location","/logout").setStatusCode(302).end();
}

Upvotes: 0

Related Questions