Skip to content

Commit ba7325c

Browse files
authored
[Vertex AI] Replace legacy errors in GenerativeAIService (#14036)
1 parent f7689cf commit ba7325c

File tree

2 files changed

+12
-11
lines changed

2 files changed

+12
-11
lines changed

FirebaseVertexAI/Sources/GenerativeAIService.swift

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -211,15 +211,16 @@ struct GenerativeAIService {
211211
}
212212

213213
private func httpResponse(urlResponse: URLResponse) throws -> HTTPURLResponse {
214-
// Verify the status code is 200
214+
// The following condition should always be true: "Whenever you make HTTP URL load requests, any
215+
// response objects you get back from the URLSession, NSURLConnection, or NSURLDownload class
216+
// are instances of the HTTPURLResponse class."
215217
guard let response = urlResponse as? HTTPURLResponse else {
216218
VertexLog.error(
217219
code: .generativeAIServiceNonHTTPResponse,
218220
"Response wasn't an HTTP response, internal error \(urlResponse)"
219221
)
220-
throw NSError(
221-
domain: "com.google.generative-ai",
222-
code: -1,
222+
throw URLError(
223+
.badServerResponse,
223224
userInfo: [NSLocalizedDescriptionKey: "Response was not an HTTP response."]
224225
)
225226
}
@@ -229,14 +230,11 @@ struct GenerativeAIService {
229230

230231
private func jsonData(jsonText: String) throws -> Data {
231232
guard let data = jsonText.data(using: .utf8) else {
232-
let error = NSError(
233-
domain: "com.google.generative-ai",
234-
code: -1,
235-
userInfo: [NSLocalizedDescriptionKey: "Could not parse response as UTF8."]
236-
)
237-
throw error
233+
throw DecodingError.dataCorrupted(DecodingError.Context(
234+
codingPath: [],
235+
debugDescription: "Could not parse response as UTF8."
236+
))
238237
}
239-
240238
return data
241239
}
242240

FirebaseVertexAI/Tests/Unit/GenerativeModelTests.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,9 @@ final class GenerativeModelTests: XCTestCase {
740740
return
741741
}
742742
XCTAssertEqual(underlyingError.localizedDescription, "Response was not an HTTP response.")
743+
let underlyingNSError = underlyingError as NSError
744+
XCTAssertEqual(underlyingNSError.domain, NSURLErrorDomain)
745+
XCTAssertEqual(underlyingNSError.code, URLError.Code.badServerResponse.rawValue)
743746
}
744747

745748
func testGenerateContent_failure_invalidResponse() async throws {

0 commit comments

Comments
 (0)