flutter 如何处理Dio包中的错误

cwxwcias  于 2023-06-24  发布在  Flutter
关注(0)|答案(2)|浏览(638)

好的,所以我使用dio包来验证我的应用程序中的用户。它工作得很好,但我希望能够在吐司消息中为用户显示错误消息,我完全不知道如何做到这一点。我试着打印错误,但我没有得到任何回应,请帮助我我是新的dio。
这是我的密码

class Loginservice extends ILogin {
  @override
  Future<UserModel?> login(
      String username, String password, BuildContext context) async {
    @override
    SharedPreferences preferences = await SharedPreferences.getInstance();

    String api = '$baseUrl/login';

    final data = {"username": username, "pwd": password};
    final dio = Dio();
    Response response;
    response = await dio.post(api, data: data);
    if (response.statusCode == 200) {
      final body = response.data;
      var username = body['username'];
      var myToken = body['token'];
      preferences.setString('username', username);
      preferences.setBool('isLoggedIn', true);

          Navigator.push(
              context, MaterialPageRoute(builder: (context) => MainScreen()));
    
          return UserModel(
            username: username,
            token: body['token'],
          );
        } else {
          print('error');
        }
      }
    }
j9per5c4

j9per5c41#

就像他们的文件里提到的,
当发生错误时,Dio会将Error/Exception Package 为DioException:
您可以使用try/ catch来捕获它们。

try {
  // 404
  await dio.get('https://api.pub.dev/not-exist');
} on DioException catch (e) {
  // The request was made and the server responded with a status code
  // that falls out of the range of 2xx and is also not 304.
  if (e.response != null) {
    print(e.response.data)
    print(e.response.headers)
    print(e.response.requestOptions)
  } else {
    // Something happened in setting up or sending the request that triggered an Error
    print(e.requestOptions)
    print(e.message)
  }
}

DioException包含这些字段,

/// The request info for the request that throws exception.
RequestOptions requestOptions;

/// Response info, it may be `null` if the request can't reach to the
/// HTTP server, for example, occurring a DNS error, network is not available.
Response? response;

/// The type of the current [DioException].
DioExceptionType type;

/// The original error/exception object;
/// It's usually not null when `type` is [DioExceptionType.unknown].
Object? error;

/// The stacktrace of the original error/exception object;
/// It's usually not null when `type` is [DioExceptionType.unknown].
StackTrace? stackTrace;

/// The error message that throws a [DioException].
String? message;

就我个人而言,我会使用switch语句来捕获所有DioExceptionType,并相应地处理/返回错误消息。

if (error is DioException) {
      switch (error.type) {
        case DioExceptionType.connectionTimeout:
        case DioExceptionType.receiveTimeout:
        case DioExceptionType.sendTimeout:
          networkFailure = const NetworkFailure.requestTimeout();
          break;
        case DioExceptionType.badCertificate:
          networkFailure = const NetworkFailure.badCertificate();
    ...

你可以找到所有的异常类型here,或者你可以简单地转到flutter应用程序中的插件源代码。

lawou6xi

lawou6xi2#

响应有两个因素:statusMessage和statusCode。
你为什么不试试这个
把A改成B
一个

} else {
      print('error');
    }

B

} else {
      print('${response.statusMessage}');
      print('${response.statusCode}');
    }

import 'dart:developer';
...
} else {
      log(response);
      log('${response.statusMessage}');
      log('${response.statusCode}');
    }

相关问题