troyzhxu / okhttps

如艺术一般优雅,像 1、2、3 一样简单,前后端通用,轻量却强大的 HTTP 客户端(同时支持 WebSocket 与 Stomp 协议)
https://ok.zhxu.cn
Apache License 2.0
485 stars 75 forks source link

在接入Stomp后,如果app网络断开,App直接奔溃,加try-catch也还是奔溃 #26

Closed yk007 closed 3 years ago

yk007 commented 3 years ago

com.ejlchina.okhttps.internal.HttpException: WebSockt 连接异常: ws://192.168.101.233:10002/api/ws/websocket at com.ejlchina.okhttps.internal.WebSocketTask$MessageListener.onFailure(WebSocketTask.java:252) at okhttp3.internal.ws.RealWebSocket.failWebSocket(RealWebSocket.java:570) at okhttp3.internal.ws.RealWebSocket$1.onFailure(RealWebSocket.java:216) at okhttp3.RealCall$AsyncCall.execute(RealCall.java:180) at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) at java.lang.Thread.run(Thread.java:776) Caused by: java.net.ConnectException: Failed to connect to /192.168.101.233:10002

yk007 commented 3 years ago
@Override
    public void onFailure(okhttp3.WebSocket webSocket, Throwable t, Response response) {
        IOException e = t instanceof IOException ? (IOException) t : new IOException(t.getMessage(), t);
        doOnClose(toState(e), 0, t.getMessage());
        TaskListener<IOException> listener = httpClient.executor.getExceptionListener();
        if (listener != null) {
            if (listener.listen(WebSocketTask.this,  e) && onException != null) {
                execute(() -> onException.on(this.webSocket,  t), exceptionOnIO);
            }
        } else if (onException != null) {
            execute(() -> onException.on(this.webSocket,  t), exceptionOnIO);
        } else if (!nothrow) {
            throw new HttpException("WebSockt 连接异常: " + getUrl(), t);
        }
    }

发现异常是在这里抛出的

troyzhxu commented 3 years ago

设置 setOnException 异常回调即可,或者使用 全局异常监听 也行。

yk007 commented 3 years ago

非常感谢,问题已解决