我正在尝试处理http错误,所以我创建了自定义http异常类

class HttpException implements Exception {
  final String message;
  HttpException(this.message);
  @override
  String toString() {
    return message;
  }
}

并抛出HTTP错误
   Future<void> createProfile(Profile profile) async {
    try {
      var request =
          new http.MultipartRequest("POST", Uri.parse(APIPath.createProfile()));
          ...
      final response = await request.send();
      if (response.statusCode != 201) {
        ...
        throw HttpException(jsonResponse["error"]);
      }

      notifyListeners();
    } catch (error) {
      print(error.runtimeType); //<= prints HttpException
      throw error;
    }
  }

当我尝试捕获它时,它仅在异常中捕获,而不在HttpExeption中捕获
      try {
        await Provider.of<User>(context, listen: false).createProfile(profile);

      } on HttpException catch (error) {
        print('Http exception'); //<- this is never reached
      } on Exception catch (error) {
        print(error.runtimeType); // <= prints HttpException
        print('exception'); //<- http exception caught here;
      } catch (error) {
        print('error');
      }

有没有机会在HttpException上处理http异常?

最佳答案

正在引用dart-io中的HttpException类,而不是自定义'HttpException'。

09-11 20:31