CoreOffice / XMLCoder

Easy XML parsing using Codable protocols in Swift
https://coreoffice.github.io/XMLCoder/
MIT License
801 stars 112 forks source link

DynamicNodeDecoding cause producing incorrect error on failure in nested struct #254

Closed Alkenso closed 1 year ago

Alkenso commented 1 year ago

The issue makes me crazy when I'm looking error logs. Probably easy to fix, but will help a lot understanding what's went wrong.

// Assume we have XML:
let xml =
"""
<Root>
   <field attr1="value_1" />
</Root>
"""

// And want to decode it into struct:
struct Model: Decodable {
    var field: Field

    struct Field: Decodable, DynamicNodeDecoding {
        var attr1: String
        var attr2: String

        static func nodeDecoding(for key: CodingKey) -> XMLDecoder.NodeDecoding {
            .attribute
        }
    }
}

// Using XMLDecoder:
do {
    _ = try XMLDecoder().decode(Model.self, from: Data(xml.utf8))
} catch {
    print(error)
}

Actual The error tells that whole property field is null

▿ DecodingError
  ▿ valueNotFound : 2 elements
    ▿ .1 : Context
      ▿ codingPath : 1 element
        - 0 : CodingKeys(stringValue: "field", intValue: nil)
      - debugDescription : "Expected Field value but found null instead."
      - underlyingError : nil

Expected If we remove conformance to DynamicNodeDecoding, we get correct error

▿ DecodingError
  ▿ keyNotFound : 2 elements
    - .0 : CodingKeys(stringValue: "attr2", intValue: nil)
    ▿ .1 : Context
      ▿ codingPath : 2 elements
        - 0 : CodingKeys(stringValue: "field", intValue: nil)
        - 1 : CodingKeys(stringValue: "attr2", intValue: nil)
      - debugDescription : "No attribute or element found for key CodingKeys(stringValue: \"attr2\", intValue: nil) (\"attr2\")."
      - underlyingError : nil
Joannis commented 1 year ago

Thanks for the bug report! I don't have time the coming week, but will make put it on my agenda after that.

Alkenso commented 1 year ago

Fixed