Skip to content

Commit ac66006

Browse files
authored
Merge pull request #95 from fabstu/exp-error
APIErrorResponse message can be [String]. Handle it.
2 parents 5959e6e + 56dd35c commit ac66006

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Sources/OpenAI/Public/Errors/APIError.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,39 @@ public struct APIError: Error, Decodable, Equatable {
1616
public let type: String
1717
public let param: String?
1818
public let code: String?
19+
20+
public init(message: String, type: String, param: String?, code: String?) {
21+
self.message = message
22+
self.type = type
23+
self.param = param
24+
self.code = code
25+
}
26+
27+
enum CodingKeys: CodingKey {
28+
case message
29+
case type
30+
case param
31+
case code
32+
}
33+
34+
public init(from decoder: Decoder) throws {
35+
let container = try decoder.container(keyedBy: CodingKeys.self)
36+
37+
//
38+
// message can be String or [String].
39+
//
40+
if let string = try? container.decode(String.self, forKey: .message) {
41+
self.message = string
42+
} else if let array = try? container.decode([String].self, forKey: .message) {
43+
self.message = array.joined(separator: "\n")
44+
} else {
45+
throw DecodingError.typeMismatch(String.self, .init(codingPath: [CodingKeys.message], debugDescription: "message: expected String or [String]"))
46+
}
47+
48+
self.type = try container.decode(String.self, forKey: .type)
49+
self.param = try container.decodeIfPresent(String.self, forKey: .param)
50+
self.code = try container.decodeIfPresent(String.self, forKey: .code)
51+
}
1952
}
2053

2154
extension APIError: LocalizedError {

0 commit comments

Comments
 (0)