diff --git a/FirebaseVertexAI/Sources/GenerativeAIService.swift b/FirebaseVertexAI/Sources/GenerativeAIService.swift index ff62a14eb19..667819c5c76 100644 --- a/FirebaseVertexAI/Sources/GenerativeAIService.swift +++ b/FirebaseVertexAI/Sources/GenerativeAIService.swift @@ -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."] ) } @@ -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 } diff --git a/FirebaseVertexAI/Tests/Unit/GenerativeModelTests.swift b/FirebaseVertexAI/Tests/Unit/GenerativeModelTests.swift index 31dbb87832d..e7571c844f3 100644 --- a/FirebaseVertexAI/Tests/Unit/GenerativeModelTests.swift +++ b/FirebaseVertexAI/Tests/Unit/GenerativeModelTests.swift @@ -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 {