Observable.just("123")
.map(new Function<String, Integer>() {
@Override
public Integer apply(String s) throws Exception {
String i = null;
i.length();
return 1;
}
}).subscribe();
这种情况下, 由于在subscribe时没有传入异常处理时的Consumer, 所以在这里会崩掉.
看一下源码:
public final Disposable subscribe() {
// 会传入一个默认的 Functions.ERROR_CONSUMER
return subscribe(Functions.emptyConsumer()
, Functions.ERROR_CONSUMER
, Functions.EMPTY_ACTION, Functions.emptyConsumer());
}
public static final Consumer<Throwable> ERROR_CONSUMER = new Consumer<Throwable>() {
@Override
public void accept(Throwable error) {
// 捕获到异常后会掉还用 RxJavaPlugins.onError.onError();
RxJavaPlugins.onError(error);
}
};
public static void onError(Throwable error) {
// 注意errorHandler
Consumer<Throwable> f = errorHandler;
if (error == null) {
error = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
}
// errorHandler不为空, 调用它的 accept() 方法, 并 return
if (f != null) {
try {
f.accept(error);
return;
} catch (Throwable e) {
e.printStackTrace(); // NOPMD
uncaught(e);
}
}
// 如果执行到这里就会抛出异常
error.printStackTrace(); // NOPMD
uncaught(error);
}
// RxjavaPlugins
static volatile Consumer<Throwable> errorHandler;
public static void setErrorHandler(Consumer<Throwable> handler) {
if (lockdown) {
throw new IllegalStateException("Plugins can't be changed anymore");
}
errorHandler = handler;
}
可以利用 上面的方法设置errorHandler, 这样当你, subscribr()不传入errorConsumer时, 就会捕获到异常不会崩掉