Search code examples
jsonswiftencodingerror-handling

What exceptions does JSONEncoder.encode throw in Swift?


I was recently using JSONEncoder.encode() (and its counterpart, JSONDecoder.decode()), which is marked in the documentation as throws. Unfortunately, the documentation does not go into detail on when/how/what this method could throw. Does anybody have any insight in this? I'm asking because I am wondering if an error here is common enough to implement a user-facing error handling for this.

thanks


Solution

  • JSONEncoder.encode() throws EncodingError.invalidValue when one of the values you are about to encode is not valid (e.g. Double.infinity if the NonConformingFloatEncodingStrategy is set to the default .throw, since JSON does not natively support infinity as a number).

    You can see this in the source, and read more about the error in the EncodingError documentation.