dart catchErrorのチェーン
catchErrorをチェーンしたときの理解があやしかったので試した
void main() async {
// catchErrorで例外を投げる
_future(true) // o:実行される x:されない
.catchError((e) => throw e) // x
.then((v) => _future(v)) // o
.catchError((e) => throw e) // o
.then((v) => _future(v)) // x
.catchError((e) => throw e); // o
// catchErrorで何もしない
_future(true)
.catchError((e) => {}) // x
.then((v) => _future(v)) // o
.catchError((e) => {}) // o
.then((v) => _future(v)) // o
.catchError((e) => {}); // o
}
Future<bool> _future(bool b) async {
if (b) {
return false;
} else {
throw Exception();
}
}catchErrorで例外を投げると次のcatchErrorは実行されてしまう。例外投げたら処理中断したい場合が多いと思うのでcatchErrorを複数チェーンするのはやめたほうが良さそう。素直にこう書く
try {
_future(true)
.then((v) => _future(v))
.then((v) => _future(v));
} catch(e) {
}以上です