'Server Response Not matching model (no records) in Swift
sorry if the question is vague but I am trying to be as expressive as possible.
I have the following model:
struct Posts: Codable, Identifiable {
let id: String
let title: String
let content: String
enum CodingKeys: String, CodingKey {
case id = "_id"
case title
case content
}
}
the server response if a post is found would be the same model no issues because the JSON matches the model .
but if the server returns an error post not found, this would be the response JSON:
{
"error": "No records found"
}
I receive the following when this happens:
keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))
what would be the best approach to handle this issue?
UPDATE:
Thank you jnpdx!
So, I did a ErrorResponse Struct, and it did catch the error response like so:
struct ErrorResponse: Codable {
let error: String
enum CodingKeys: String, CodingKey {
case error
}
}
So in my APIServices file, how do I handle this?
// this is what gets the Post data
let decodedData = try JSONDecoder().decode(Post?.self, from: data)
//Do I need another JSONDecoder to also catch the error below the above line like this?
let decodedDataError = try JSONDecoder().decode(ErrorResponse?.self, from: data)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
