Android 调用函数未捕获从另一个类抛出的颤振错误
我在flatter中有一个this bloc实现,所以一旦触发了bloc,它就会调用apiCall()函数,如下所示Android 调用函数未捕获从另一个类抛出的颤振错误,android,flutter,error-handling,Android,Flutter,Error Handling,我在flatter中有一个this bloc实现,所以一旦触发了bloc,它就会调用apiCall()函数,如下所示 Future apiCall() async { print("calling api now "); var future = repository.getList().catchError((err) { print("api_bloc:Error is " + err.toString()); if(err is AuthError)
Future apiCall() async {
print("calling api now ");
var future = repository.getList().catchError((err) {
print("api_bloc:Error is " + err.toString());
if(err is AuthError){
print("Auth error");
}
});
}
这将调用存储库函数repository.getList(),如下所示
Future<CountyListRoot> getList() async {
String url = "countyList";
try{
final countyListJson = await NetworkUtils.postNoToken(url).catchError((err) {
print("county list repository is " + err.toString());
if(err is AuthError){
print("catch at repository Auth error");
throw AuthError('Auth Error: ');
}
});
print("countyListJson" + countyListJson.toString());
return CountyListRoot.fromJson(countyListJson);
}
catch(exception){
if(exception is AuthError){
print("catch at repository Auth error");
}
print("Exception");
}
}
所以在上面的场景中,我特意创建了一个生成
if(code==401){
throw AuthError('$code Auth Error: '+parseMessage(response.body));
}
但它没有在存储库函数中捕获或显示。
下面我也创建了模型
class UnknownError {
final String message;
UnknownError(this.message);
}
class DiffError{
final String message;
DiffError(this.message);
}
class AuthError {
final String message;
AuthError(this.message);
}
class Error4xx {
final String message;
Error4xx(this.message);
}
如何修复捕获和传递此错误,以便最终通过一些snackbar或相应的弹出窗口显示?当捕获异常时,需要
重新播放它,以便调用方能够捕获它
因此,无论您当前在何处捕获到异常,如果该异常未由特定捕获处理,您都应该重新捕获
void misbehave() {
try {
dynamic foo = true;
print(foo++); // Runtime error
} catch (e) {
print('misbehave() partially handled ${e.runtimeType}.');
rethrow; // Allow callers to see the exception.
}
}
void main() {
try {
misbehave();
} catch (e) {
print('main() finished handling ${e.runtimeType}.');
}
}
所以,我应该在每一个地方投一次球,然后换成再投,是吗?问题是,第一次投的球也没有被抓住,所以在我的情况下,如何再投一次球?不,应该放在你的接球区。每次捕获异常但不处理它时,都应该重新刷新,以便调用方能够捕获它。我已经添加了一些示例代码。在我的例子中,我没有得到第一个抛出的位置是这样的:抛出AuthError(“$code Auth Error:”+parseMessage(response.body));所以如何将它转换为rethrow,因为我看到rethrow必须是rethrow;以分号结束也是另一个问题,这个抛出没有被捕获在异常中,因为我基于http返回的响应代码
void misbehave() {
try {
dynamic foo = true;
print(foo++); // Runtime error
} catch (e) {
print('misbehave() partially handled ${e.runtimeType}.');
rethrow; // Allow callers to see the exception.
}
}
void main() {
try {
misbehave();
} catch (e) {
print('main() finished handling ${e.runtimeType}.');
}
}