eclipse-vertx / vert.x

Vert.x is a tool-kit for building reactive applications on the JVM
http://vertx.io
Other
14.25k stars 2.06k forks source link

ServerWebSocket handler should not ignore exception #2948

Open FulaiZhang-cn opened 5 years ago

FulaiZhang-cn commented 5 years ago

here is reproduce code:

import io.vertx.core.AbstractVerticle; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpServer; import io.vertx.core.http.ServerWebSocket; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext;

public class ReproduceWebSocketException extends AbstractVerticle {

public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    vertx.deployVerticle(new ReproduceWebSocketException(), ar->{
        runClient(vertx);
    });
}

private static void runClient(Vertx vertx) {
    HttpClient client = vertx.createHttpClient();
    client.websocket(8088,"localhost", "/", ws->{
        for (int i = 0; i < 10; i++) {
            ws.write(Buffer.buffer("hello"));
        }
    });
}

@Override
public void start() throws Exception {
    HttpServer server = vertx.createHttpServer();
    Router router = Router.router(vertx);
    router.route("/").handler(this::handlerWebsocket);
    server.requestHandler(router).listen(8088);

    System.out.println("server started");
}

private void handlerWebsocket(RoutingContext context) {
    ServerWebSocket socket = context.request().upgrade();
    socket.handler(buff->{
        System.out.println("got buffer:" + buff.toString());

        //this exception is ignored
        throw new RuntimeException("error");
    });
    socket.closeHandler(v->{
        System.out.println("close");
    });
    socket.exceptionHandler(th->{
        th.printStackTrace();
    });
}

}

there have a exception throwed in :

socket.handler(buff->{ System.out.println("got buffer:" + buff.toString());

    //this exception is ignored
    throw new RuntimeException("error");
});

while I am debugging source code, found that InboundBuffer<Buffer> pending in WebSocketImplBase doesn't setup exceptionHandler. so I think this is a bug.

doctorpangloss commented 4 years ago

exceptionHandler is for exceptions thrown by the stream, i.e. a closed connection (SocketException), not for exceptions thrown by your user-supplied handler. If you'd like to handle those exceptions wrap your handler in a try-catch.