如果问题很模糊,我很抱歉,但我正在尽可能地表达。
我有以下型号:
struct Posts: Codable, Identifiable {
let id: String
let title: String
let content: String
enum CodingKeys: String, CodingKey {
case id = "_id"
case title
case content
}
}
如果找到帖子,服务器的响应将是相同的模型——没有问题,因为JSON与模型匹配。
但是,如果服务器返回一个未找到的错误帖子,这将是响应JSON:
{
"error": "No records found"
}
当这种情况发生时,我会收到以下信息:
keyNotFound(编码键(字符串值:"id",intValue:nil(,Swift。DecodingError.Context(编码路径:[],调试描述:"没有与键编码键关联的值(字符串值;id",int值:nil(("id"(&";,underlyingError:nil((
处理此问题的最佳方法是什么?
更新:
谢谢你jnpdx!
所以,我做了一个ErrorResponse Struct,它确实捕捉到了这样的错误响应:
struct ErrorResponse: Codable {
let error: String
enum CodingKeys: String, CodingKey {
case error
}
}
那么,在我的APIServices文件中,我该如何处理?
// 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)
在评论中,我们讨论了创建一个结构来对错误进行建模,看起来就像您已经完成了。为了解决您的后续问题,不,您不需要单独的JSONDecoder
。您可能也不应该解码选项。
不仅有一种方法可以正确地做到这一点,而且您的函数可能看起来像这样:
let decoder = JSONDecoder()
do {
let post = try decoder.decode(Post.self, from: data)
//handle the post
} catch {
//try to decode an error
if let error = try? decoder.decode(ErrorResponse.self, from: data) {
//handle an API error
}
//handle an unknown error
}