解码来自Dart中捕获的响应
我尝试解码捕获返回的响应,以下是我尝试的:解码来自Dart中捕获的响应,dart,Dart,我尝试解码捕获返回的响应,以下是我尝试的: try{ ... } catch (err) { //JsonCodec codec = new JsonCodec(); // doesn't work //var decoded = codec.decode(err); ... } 错误:类型“\u Exception”不是“String”类型的子类型 打印错误: 例外情况:{ 错误:{ 代码:无效\u到期\u年 } } 我想了解代码的价值,我尝试了很多方法,但都不
try{
...
} catch (err) {
//JsonCodec codec = new JsonCodec(); // doesn't work
//var decoded = codec.decode(err);
...
}
错误:类型“\u Exception”不是“String”类型的子类型
打印错误:
例外情况:{
错误:{
代码:无效\u到期\u年
}
}
我想了解代码的价值,我尝试了很多方法,但都不起作用
有什么想法吗
print(err.code);
然后我得到:
我终于想出了一个解决办法:
catch (response) {
var err=response.toString().replaceAll('Exception: ', '');
final json=JSON.jsonDecode(err);
print(json['error']['code']);
}
您可以获取消息属性并对其进行jsonDecode
所有这些都被认为是对例外的滥用。请注意,您通常不希望抛出Exceptionmessage;。将json编码的消息放入其中并不是传达异常详细信息的最佳方式。相反,编写异常的自定义实现并捕获特定类型
class InvalidDataException implements Exception {
final String code;
InvalidDataException(this.code);
}
try {
} on InvalidDataException catch(e) {
print(e.code); // guaranteed to work, we know the type of the exception
}
见:
不鼓励直接使用新的Exceptionmessage创建异常实例,在库使用的实际异常完成之前,只将其作为开发期间的临时措施包括在内
另请参见错误代码不起作用?看起来不需要decoding@SterlingArcher我用我得到的更新了问题,知道吗?
class InvalidDataException implements Exception {
final String code;
InvalidDataException(this.code);
}
try {
} on InvalidDataException catch(e) {
print(e.code); // guaranteed to work, we know the type of the exception
}