Skip to content

Commit

Permalink
[Vertex AI] Replace legacy errors in GenerativeAIService (#14036)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewheard authored Nov 5, 2024
1 parent f7689cf commit ba7325c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
20 changes: 9 additions & 11 deletions FirebaseVertexAI/Sources/GenerativeAIService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -211,15 +211,16 @@ struct GenerativeAIService {
}

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

private func jsonData(jsonText: String) throws -> Data {
guard let data = jsonText.data(using: .utf8) else {
let error = NSError(
domain: "com.google.generative-ai",
code: -1,
userInfo: [NSLocalizedDescriptionKey: "Could not parse response as UTF8."]
)
throw error
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: [],
debugDescription: "Could not parse response as UTF8."
))
}

return data
}

Expand Down
3 changes: 3 additions & 0 deletions FirebaseVertexAI/Tests/Unit/GenerativeModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,9 @@ final class GenerativeModelTests: XCTestCase {
return
}
XCTAssertEqual(underlyingError.localizedDescription, "Response was not an HTTP response.")
let underlyingNSError = underlyingError as NSError
XCTAssertEqual(underlyingNSError.domain, NSURLErrorDomain)
XCTAssertEqual(underlyingNSError.code, URLError.Code.badServerResponse.rawValue)
}

func testGenerateContent_failure_invalidResponse() async throws {
Expand Down

0 comments on commit ba7325c

Please sign in to comment.