如何在 catch 代码中访问 dio onResponse.statuscode
How to access dio onResponse.statuscode in catch code
我正在尝试创建一个登录表单,当服务器未 运行、凭据无效以及未连接互联网时,我试图在其中显示弹出对话框。这是我的代码。
var data={};
Future login() async {
Dio dio = new Dio();
try {
data = {
'username':user.username,
'password':user.password,
'date': formattedDate
};
await dio
.post(localhostUrlLogin, data: json.encode(data),)
.then((onResponse) async {
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Navigation()));
});
} catch (e) {
print(OSError.noErrorCode);
if (OSError.noErrorCode== -1) {
showDialog(
context: context,
builder: (BuildContext context) {
return AdvanceCustomAlert(
title: "Connection Error",
descriptions: "Connection error",
icon: Icons.error,
bgcolor: Colors.red,
fgcolor: Colors.red,
);
});
} else {
print("con er");
showDialog(
context: context,
builder: (BuildContext context) {
return AdvanceCustomAlert(
title: "Try Again",
descriptions: "Invalid username or password!",
icon: Icons.error,
bgcolor: Colors.red,
fgcolor: Colors.red,
);
});
}
}
}
我在所有条件下都得到 OSError.noErrorCode
-1,我在后端传递 无效输入 错误 (api) 但我不能在 try 代码之后访问 onResponse。
请告诉我如何做到这一点。
您可以通过以下方式正确处理dio错误
try {
Response response = await allDataRepository.getData();
print(response.toString());
} on DioError catch (dioError) {
print(dioError);
if (dioError.type == DioErrorType.response) {
switch (dioError.response!.statusCode) {
case 404:
log(error: '400 - Not found');
break;
case 401:
log(error: '401 - Unauthorized.');
break;
case 500:
log(error: '500 - Internal Server Error.');
break;
case 501:
log(error: '501 - Not Implemented Server Error.');
break;
case 502:
log(error: '502 - Bad Gateway Server Error.');
break;
default:
log(error: '${dioError.response!.statusCode} - Something went wrong while trying to connect with the server');
break;
}
} else if (dioError.type == DioErrorType.other) {
log(error: 'Please check your internet connection. Try again switching to a different connection');
}
} catch (e) {
log(error: 'Something went wrong : $e');
}
存储库应如下所示 (data_repository.dart)
class DataRepository {
final HttpClient httpClient;
DataRepository({required this.httpClient});
Future<Response> getData() async {
Response response = await httpClient.dio.get(
GlobalConfig.getDataUrl,
);
return response;
}
}
HttpClient 应如下所示 (http_client.dart)
class HttpClient {
final Dio dio;
HttpClient({required this.dio});
static final String basePath = GlobalConfig.baseUrl;
void addBasePathInterceptor() {
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
print(options.uri);
if (!options.path.startsWith("http")) {
options.baseUrl = basePath;
}
return handler.next(options);
},
));
addUrlInterceptor();
// addVersionInterceptor();
}
Interceptor? sessionCookieInterceptor;
Interceptor? versionCookieInterceptor;
Interceptor? status401Interceptor;
// void addSessionCookieInterceptor(List<String> cookies) {
// sessionCookieInterceptor = InterceptorsWrapper(
// onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
// options.headers['cookie'] = cookies.join(';');
// });
// dio.interceptors.add(sessionCookieInterceptor!);
// }
// void addVersionInterceptor() {
// versionCookieInterceptor = InterceptorsWrapper(
// onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
// options.headers['website-version'] = '26.3.0';
// });
// dio.interceptors.add(versionCookieInterceptor!);
// }
void addUrlInterceptor() {
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
print('onRequest ${options.uri}');
return handler.next(options);
},
onResponse: (Response response, ResponseInterceptorHandler handler) {
print('onResponse ${response.statusCode} ${response.realUri}');
return handler.next(response);
},
onError: (DioError error, ErrorInterceptorHandler handler) {
if (error.type == DioErrorType.response) {
print('------------------------');
print(error.error);
print(error.response?.realUri);
print(error.response?.statusCode);
print(error.response?.data);
print('------------------------');
}
return handler.next(error);
},
));
}
void add401Interceptor() {
print("Adding 401 interceptor");
status401Interceptor = InterceptorsWrapper(
onError: (DioError res, ErrorInterceptorHandler handler) {
if (res.response != null && res.response?.statusCode == 401) {
// globalBloc.add(ShowErrorSnackBar(
// error: 'You have been logged out, Please login again'));
// authenticationBloc.add(AuthenticationUnauthenticatedEvent());
// mainBloc.add(LougoutEvent());
}
return handler.next(res);
});
dio.interceptors.add(status401Interceptor!);
}
// void remove401Interceptor() {
// dio.interceptors.remove(status401Interceptor);
// }
}
最后,在 main.dart
中初始化 HttpClient,如下所示
void main() async {
// Intializing Http Client
HttpClient(dio: sl()).addBasePathInterceptor();
runApp(MyApp());
}
请注意,您只需要下面这一堆代码。但我已经描述了一种处理应用程序中每个 API 调用的好方法。
Dio dio = new Dio();
try {
Response response = await dio.get(GlobalConfig.getDataUrl);
print(response.toString());
} on DioError catch (dioError) {
print(dioError);
if (dioError.type == DioErrorType.response) {
switch (dioError.response!.statusCode) {
case 404:
log(error: '400 - Not found');
break;
case 401:
log(error: '401 - Unauthorized.');
break;
case 500:
log(error: '500 - Internal Server Error.');
break;
case 501:
log(error: '501 - Not Implemented Server Error.');
break;
case 502:
log(error: '502 - Bad Gateway Server Error.');
break;
default:
log(error: '${dioError.response!.statusCode} - Something went wrong while trying to connect with the server');
break;
}
} else if (dioError.type == DioErrorType.other) {
log(error: 'Please check your internet connection. Try again switching to a different connection');
}
} catch (e) {
log(error: 'Something went wrong : $e');
}
我正在尝试创建一个登录表单,当服务器未 运行、凭据无效以及未连接互联网时,我试图在其中显示弹出对话框。这是我的代码。
var data={};
Future login() async {
Dio dio = new Dio();
try {
data = {
'username':user.username,
'password':user.password,
'date': formattedDate
};
await dio
.post(localhostUrlLogin, data: json.encode(data),)
.then((onResponse) async {
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Navigation()));
});
} catch (e) {
print(OSError.noErrorCode);
if (OSError.noErrorCode== -1) {
showDialog(
context: context,
builder: (BuildContext context) {
return AdvanceCustomAlert(
title: "Connection Error",
descriptions: "Connection error",
icon: Icons.error,
bgcolor: Colors.red,
fgcolor: Colors.red,
);
});
} else {
print("con er");
showDialog(
context: context,
builder: (BuildContext context) {
return AdvanceCustomAlert(
title: "Try Again",
descriptions: "Invalid username or password!",
icon: Icons.error,
bgcolor: Colors.red,
fgcolor: Colors.red,
);
});
}
}
}
我在所有条件下都得到 OSError.noErrorCode
-1,我在后端传递 无效输入 错误 (api) 但我不能在 try 代码之后访问 onResponse。
请告诉我如何做到这一点。
您可以通过以下方式正确处理dio错误
try {
Response response = await allDataRepository.getData();
print(response.toString());
} on DioError catch (dioError) {
print(dioError);
if (dioError.type == DioErrorType.response) {
switch (dioError.response!.statusCode) {
case 404:
log(error: '400 - Not found');
break;
case 401:
log(error: '401 - Unauthorized.');
break;
case 500:
log(error: '500 - Internal Server Error.');
break;
case 501:
log(error: '501 - Not Implemented Server Error.');
break;
case 502:
log(error: '502 - Bad Gateway Server Error.');
break;
default:
log(error: '${dioError.response!.statusCode} - Something went wrong while trying to connect with the server');
break;
}
} else if (dioError.type == DioErrorType.other) {
log(error: 'Please check your internet connection. Try again switching to a different connection');
}
} catch (e) {
log(error: 'Something went wrong : $e');
}
存储库应如下所示 (data_repository.dart)
class DataRepository {
final HttpClient httpClient;
DataRepository({required this.httpClient});
Future<Response> getData() async {
Response response = await httpClient.dio.get(
GlobalConfig.getDataUrl,
);
return response;
}
}
HttpClient 应如下所示 (http_client.dart)
class HttpClient {
final Dio dio;
HttpClient({required this.dio});
static final String basePath = GlobalConfig.baseUrl;
void addBasePathInterceptor() {
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
print(options.uri);
if (!options.path.startsWith("http")) {
options.baseUrl = basePath;
}
return handler.next(options);
},
));
addUrlInterceptor();
// addVersionInterceptor();
}
Interceptor? sessionCookieInterceptor;
Interceptor? versionCookieInterceptor;
Interceptor? status401Interceptor;
// void addSessionCookieInterceptor(List<String> cookies) {
// sessionCookieInterceptor = InterceptorsWrapper(
// onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
// options.headers['cookie'] = cookies.join(';');
// });
// dio.interceptors.add(sessionCookieInterceptor!);
// }
// void addVersionInterceptor() {
// versionCookieInterceptor = InterceptorsWrapper(
// onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
// options.headers['website-version'] = '26.3.0';
// });
// dio.interceptors.add(versionCookieInterceptor!);
// }
void addUrlInterceptor() {
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
print('onRequest ${options.uri}');
return handler.next(options);
},
onResponse: (Response response, ResponseInterceptorHandler handler) {
print('onResponse ${response.statusCode} ${response.realUri}');
return handler.next(response);
},
onError: (DioError error, ErrorInterceptorHandler handler) {
if (error.type == DioErrorType.response) {
print('------------------------');
print(error.error);
print(error.response?.realUri);
print(error.response?.statusCode);
print(error.response?.data);
print('------------------------');
}
return handler.next(error);
},
));
}
void add401Interceptor() {
print("Adding 401 interceptor");
status401Interceptor = InterceptorsWrapper(
onError: (DioError res, ErrorInterceptorHandler handler) {
if (res.response != null && res.response?.statusCode == 401) {
// globalBloc.add(ShowErrorSnackBar(
// error: 'You have been logged out, Please login again'));
// authenticationBloc.add(AuthenticationUnauthenticatedEvent());
// mainBloc.add(LougoutEvent());
}
return handler.next(res);
});
dio.interceptors.add(status401Interceptor!);
}
// void remove401Interceptor() {
// dio.interceptors.remove(status401Interceptor);
// }
}
最后,在 main.dart
中初始化 HttpClient,如下所示void main() async {
// Intializing Http Client
HttpClient(dio: sl()).addBasePathInterceptor();
runApp(MyApp());
}
请注意,您只需要下面这一堆代码。但我已经描述了一种处理应用程序中每个 API 调用的好方法。
Dio dio = new Dio();
try {
Response response = await dio.get(GlobalConfig.getDataUrl);
print(response.toString());
} on DioError catch (dioError) {
print(dioError);
if (dioError.type == DioErrorType.response) {
switch (dioError.response!.statusCode) {
case 404:
log(error: '400 - Not found');
break;
case 401:
log(error: '401 - Unauthorized.');
break;
case 500:
log(error: '500 - Internal Server Error.');
break;
case 501:
log(error: '501 - Not Implemented Server Error.');
break;
case 502:
log(error: '502 - Bad Gateway Server Error.');
break;
default:
log(error: '${dioError.response!.statusCode} - Something went wrong while trying to connect with the server');
break;
}
} else if (dioError.type == DioErrorType.other) {
log(error: 'Please check your internet connection. Try again switching to a different connection');
}
} catch (e) {
log(error: 'Something went wrong : $e');
}