0

In my app, I'm using Alamofire as network library. I have an object like this (all properties are non-optional)

struct User: Codable {
   let name: String
   let email: String
   let role: String
}

In the network I have a function that invoke an API HTTP to fetch User as array of users:

.responseDecodable(of: [User].self)

the problem is: is possible to find inside the database some user that was created in a bad way without all mandatory fields, so the Decodable fails. I expected to have an array without this broken user, instead all the decode fails anche the request fails with an error like

responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "role", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "role", intValue: nil), CodingKeys(stringValue: "time", intValue: nil)], debugDescription: "Expected String value but found null instead.", underlyingError: nil))))

Is there a way to use the power of responseDecodable without having this error and simply discard the broken user?

Thanks in advance.

Fry
  • 6,235
  • 8
  • 54
  • 93
  • You can declare the affected properties as optional or you can implement `init(from decoder:)` and add the logic to handle the bad users. Or prevent the API from creating bad users. – vadian Apr 06 '23 at 21:22
  • I'd also go with a clean up of the data base. Either put empty string for needed values, or remove them. – Larme Apr 07 '23 at 07:45
  • This is a `Decodable` issue, not an Alamofire issue. There are a variety of existing solutions for decoding arrays where it doesn't produce an error when an element can't be decoded. – Jon Shier Apr 07 '23 at 17:32
  • @JonShier can you explain me this solutions? Thanks – Fry Apr 08 '23 at 15:02
  • https://stackoverflow.com/questions/46344963/swift-jsondecode-decoding-arrays-fails-if-single-element-decoding-fails ? – Larme Apr 12 '23 at 08:07

0 Answers0