woj*_*ski 6 android onerror rx-java retrofit2
我想知道你在改造Rx onError时处理不同类型错误(如http异常,没有互联网连接异常等)的方法,而不使用instanceof像这里提到的那样:如何使用RxJava处理Retrofit 2中的网络错误或处理:处理错误在Retrofit 2 RX中
在kotlin中,我将简单地为每种throwable做一些扩展函数来做我想做的事情.
但是我被迫在项目中使用Java.有什么好建议吗?
是构建某种错误处理程序的方法,如下所示:
public interface ErrorHandler {
void handleError(Exception e);
void handleError(HttpException e);
void handleError(NullPointerException npe);
}
Run Code Online (Sandbox Code Playgroud)
好?我知道这不是因为每次我需要处理另一个特定的错误我被迫改变界面,所以它违反了Open Close Principle.但我无法找出任何解决方案.
欢呼Wojtek
编译器决定调用哪个方法,而不是虚拟机。因此,除非您首先检查 instanceof 并将参数转换为正确的类型,否则您描述的类无法解决问题。否则你每次都会得到handleError(Exception e)。
但我想创建一个答案并不是因为这个原因,而是为了论证在许多情况下只有一个错误处理程序实际上是更好的选择,而不是一种责任。在 Java 中,我们经常会遇到这样的可怕情况:
catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No such algorithm: RSA?", e);
}
catch (NoSuchProviderException e) {
throw new IllegalStateException("No such provider: " + ANDROID_KEYSTORE_ID, e);
}
catch (InvalidAlgorithmParameterException e) {
throw new IllegalStateException("Bug setting up encryption key for user credentials: ", e);
}
catch (KeyStoreException e) {
throw new IllegalStateException("Bug setting up encryption key for user credentials: ", e);
}
catch (IOException e) {
Log.w(TAG, "Exception setting up keystore for user creds. They won't be stored.", e);
}
catch (CertificateException e) {
Log.w(TAG, "Exception setting up keystore for user creds. They won't be stored.", e);
}
Run Code Online (Sandbox Code Playgroud)
仅拥有一个错误处理程序使我们能够将多种类型的异常集中在一起。您可以在这段代码中看到,有些异常是永远不应该抛出的,有些异常实际上只能是代码中错误的结果,有些是我们需要处理的合法异常状态。我觉得这很混乱,我想说:
if (e instanceof NoSuchAlgorithmException || e instanceof NoSuchProviderException) {
Log.wtf(TAG, "What the heck is this?", e);
throw new IllegalStateException("This is some kind of weird bug", e);
}
else if (e instanceof IOException || e instanceof CertificateException) {
// This can happen sometimes, track event in analytics and perhaps
// try some alternative means of credential storage.
}
else {
// At least here the app won't crash if some unexpected exception occurs,
// since we're trapping everything.
}
Run Code Online (Sandbox Code Playgroud)
我不认为能够将意外故障集中在一起并以比崩溃应用程序更用户友好的方式处理它们是一件坏事。即使这只是一个错误,最好在幕后的分析框架中跟踪它,而不是将用户从应用程序中轰炸出来。Android 应用程序中的许多崩溃实际上是完全可以恢复的,但我们不会在每个 try/catch 语句中都捕获 Throwable,因为它需要大量额外代码。
| 归档时间: |
|
| 查看次数: |
604 次 |
| 最近记录: |