解码Dart中的捕获响应 [英] Decode a response from a catch in Dart
问题描述
我尝试解码从捕获返回的响应,这是我尝试的内容:
I try to decode the response returned from a catch, here is what I tried :
try{
...
} catch (err) {
//JsonCodec codec = new JsonCodec(); // doesn't work
//var decoded = codec.decode(err);
...
}
错误:类型'_Exception'不是类型'字符串'的子类型
Error: type '_Exception' is not a subtype of type 'String'
print(err):
print(err) :
例外:{
error:{
code: invalid_expiry_year
}
}
Exception: { "error": { "code": "invalid_expiry_year" } }
我想获取代码的值,我尝试了很多事情,但没有用,
I would like to get the value of "code", I tried many things but it doesn't work,
有什么想法吗?
print(err.code);
然后我得到:
推荐答案
您可以获取 message
属性和 jsonDecode
它。
try {
} catch (e) {
var message = e.message; // not guaranteed to work if the caught exception isn't an _Exception instance
var decoded = jsonDecode(message);
print(decoded['error']['code'])'
}
所有这些警告都是对 Exception
的滥用。请注意,您通常不要引发异常(消息);
。将json编码的消息放入其中并不是传达有关异常的详细信息的最佳方法。而是编写一个 Exception
的自定义实现并捕获特定类型。
All of this strikes as a misuse of Exception
. Note that you generally don't want to throw Exception(message);
. Putting a json encoded message in there is not the best way to communicate details about the exception. Instead, write a custom implementation of Exception
and catch the specific type.
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
}
请参见< a href = https://api.dartlang.org/stable/2.1.0/dart-core/Exception-class.html rel = nofollow noreferrer> Exception $ c的文档$ c> :
直接使用
new Exception( message)<<不鼓励使用/ code>,并且仅在开发过程中将其作为临时措施使用,直到完成库使用的实际例外为止。
Creating instances of Exception directly with
new Exception("message")
is discouraged, and only included as a temporary measure during development, until the actual exceptions used by a library are done.
另请参见 https:/ /www.dartlang.org/guides/language/effective-dart/usage#avoid-catches-with-on-clauses
这篇关于解码Dart中的捕获响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!