From c2e55f11abc4fb8a7cdcaa6a98192ad5e21f4c4d Mon Sep 17 00:00:00 2001 From: Edgar <19417672+grundmanise@users.noreply.github.com> Date: Mon, 11 Aug 2025 20:03:51 +0300 Subject: [PATCH] Support integer code in OpenAI error responses (e.g. for OpenRouter) --- .../ResponseModels/OpenAIErrorResponse.swift | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/Sources/OpenAI/Public/ResponseModels/OpenAIErrorResponse.swift b/Sources/OpenAI/Public/ResponseModels/OpenAIErrorResponse.swift index ac89412a..bee80d03 100644 --- a/Sources/OpenAI/Public/ResponseModels/OpenAIErrorResponse.swift +++ b/Sources/OpenAI/Public/ResponseModels/OpenAIErrorResponse.swift @@ -24,5 +24,26 @@ public struct OpenAIErrorResponse: Decodable { public let type: String? public let param: String? public let code: String? + + enum CodingKeys: String, CodingKey { + case message, type, param, code + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + message = try container.decodeIfPresent(String.self, forKey: .message) + type = try container.decodeIfPresent(String.self, forKey: .type) + param = try container.decodeIfPresent(String.self, forKey: .param) + + // Some OpenAI-compatible providers (e.g. OpenRouter) provide literal response status codes in the "code" field (e.g., 403) + // Try decoding "code" first as an Int, then fallback to a String + if let intCode = try? container.decodeIfPresent(Int.self, forKey: .code) { + code = String(intCode) + } else if let stringCode = try? container.decodeIfPresent(String.self, forKey: .code) { + code = stringCode + } else { + code = nil + } + } } -} +} \ No newline at end of file