【问题标题】:How can I fix: Unhandled Exception: type 'SocketException' is not a subtype of type 'String'?我该如何解决:未处理的异常:“SocketException”类型不是“String”类型的子类型?
【发布时间】:2020-04-18 20:03:28
【问题描述】:

这个函数会产生错误:

static Future<String> createTable() async {
try {
  var map = Map<String, dynamic>();
  map['action'] = 'CREATE_TABLE';
  final response = await http.post(ROOTurl, body: map);
  print('Create Table Response: ${response.body}');
  if (200 == response.statusCode) {
    return response.body;
  } else {
    return "error";
  }
} catch (e) {
  return "error"+e;
}}

完全例外:

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'SocketException' is not a subtype of type 'String'

有什么办法可以解决这个问题?

【问题讨论】:

  • 而不是'return "error"+e'尝试写'return "error ${e.message}"'

标签: flutter dart


【解决方案1】:

您正在尝试将String 与非字符串类型连接

试试这个:

  try {
    //code throwing exceptions
  } on SocketException catch (e) {
    print('error ${e.message}');
  } catch (e) {
    //for other errors
    print('error ${e.toString()}');
  }

【讨论】:

  • ${e.message} 没用,${e} 没用,谢谢!但是现在出现了这个错误: I/flutter (17320): error SocketException: OS Error: Connection denied, errno = 111, address = localhost, port = 49958
  • 现在这是一个安全错误,与问题无关,但奇怪的是它不起作用,因为文档说 SocketException 类有一个消息属性(@987654321 @)
  • 我通过将 url 中的 'localhost' 替换为我的 ip 地址来修复它,现在一切正常。感谢您的回答!
  • @Fenerbahce 请查看编辑答案首先不起作用,因为如果您不指定异常类型,那么类型将是抽象异常,它没有消息属性,而 SocketException 有这个属性
猜你喜欢
  • 2021-09-19
  • 2021-07-18
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多