【发布时间】:2020-07-13 09:31:00
【问题描述】:
在 Android 平台上处理来自 getMessage() 的消息异常是否是一种好习惯?
在我的 android 应用程序中,我有以下类:
public class Test {
boolean alreadyTried;
public Test() {
alreadyTried = false;
}
private void doTest() {
try {
downloadPictureFromServer(); //uses okhttp3
} catch (Exception e) {
if(e.getMessage() != null && e.getMessage().contains("Connection reset by peer")){
//try again (only once)
if(alreadyTried) {
Log.e("Test", "Connection reset by peer repeatedly, cannot communicate with the server");
} else {
Log.e("Test", "Connection reset by peer, trying to communicate with the server again...");
alreadyTried = true;
doTest(); //try again
}
} else {
throw e;
}
}
}
}
当 doTest() 被调用时,它开始与运行在 Tomcat 服务器上的 Web 应用程序通信,有时会抛出以下异常:
javax.net.ssl.SSLHandshakeException:SSL 握手中止:ssl=0x7653281108:系统调用期间的 I/O 错误,对等方重置连接
这不太可能发生,但它可能会在服务器重新启动时发生......等等。我在测试期间已经发生了不止一次。
那么,我可以使用该消息并安全地检查它是否包含“Connection reset by peer”字符串吗?或者来自 getMessage() 的消息是否有可能使用与英语不同的语言?
我试图查找此信息,但我找不到任何地方...我想确保可以像本示例中那样处理它并让我的头脑平静下来。我还尝试将我的 android 设备中的语言更改为德语或捷克语,但异常消息仍然是英语,所以这是一个好兆头。
更新: 关于 Stephen C 的回答,我将 if 条件更改为:
if(e instanceof SSLHandshakeException) {
//try again (only once)
...
}
这对于异常没有那么具体,但使用起来更安全。
【问题讨论】:
标签: java android android-studio exception