【问题标题】:What exceptions does JSONEncoder.encode throw in Swift?JSONEncoder.encode 在 Swift 中会抛出什么异常?
【发布时间】:2018-01-08 16:08:57
【问题描述】:
我最近在使用JSONEncoder.encode()(及其对应的JSONDecoder.decode()),在the documentation 中标记为throws。不幸的是,该文档没有详细说明该方法何时/如何/抛出什么。有人对此有任何见解吗?我之所以问,是因为我想知道这里的错误是否足够普遍,可以为此实现面向用户的错误处理。
谢谢
【问题讨论】:
标签:
json
swift
encoding
error-handling
【解决方案1】:
JSONEncoder.encode() 当您要编码的值之一无效时抛出EncodingError.invalidValue(例如Double.infinity,如果NonConformingFloatEncodingStrategy 设置为默认.throw,因为JSON 本身不支持无穷大一个数字)。
您可以在source 中看到这一点,并在EncodingError documentation 中阅读有关错误的更多信息。