Skip to content

Commit bb9563f

Browse files
paulb777G.Dev.Ssomsak
authored andcommitted
Capture and share the backend's message for an invalid API key (google-gemini#120)
1 parent 1ed073f commit bb9563f

File tree

4 files changed

+5
-5
lines changed

4 files changed

+5
-5
lines changed

Examples/GenerativeAISample/ChatSample/Views/ErrorDetailsView.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ struct ErrorDetailsView: View {
239239
}
240240

241241
#Preview("Invalid API Key") {
242-
ErrorDetailsView(error: GenerateContentError.invalidAPIKey)
242+
ErrorDetailsView(error: GenerateContentError.invalidAPIKey(message: "Fix API key placeholder"))
243243
}
244244

245245
#Preview("Unsupported User Location") {

Sources/GoogleAI/GenerateContentError.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public enum GenerateContentError: Error {
3030
case responseStoppedEarly(reason: FinishReason, response: GenerateContentResponse)
3131

3232
/// The provided API key is invalid.
33-
case invalidAPIKey
33+
case invalidAPIKey(message: String)
3434

3535
/// The user's location (region) is not supported by the API.
3636
///

Sources/GoogleAI/GenerativeModel.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ public final class GenerativeModel {
318318
if let error = error as? GenerateContentError {
319319
return error
320320
} else if let error = error as? RPCError, error.isInvalidAPIKeyError() {
321-
return GenerateContentError.invalidAPIKey
321+
return GenerateContentError.invalidAPIKey(message: error.message)
322322
} else if let error = error as? RPCError, error.isUnsupportedUserLocationError() {
323323
return GenerateContentError.unsupportedUserLocation
324324
}

Tests/GoogleAITests/GenerativeModelTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,8 +248,8 @@ final class GenerativeModelTests: XCTestCase {
248248
do {
249249
_ = try await model.generateContent(testPrompt)
250250
XCTFail("Should throw GenerateContentError.internalError; no error thrown.")
251-
} catch GenerateContentError.invalidAPIKey {
252-
// Do nothing, catching a GenerateContentError.invalidAPIKey error is expected.
251+
} catch let GenerateContentError.invalidAPIKey(message) {
252+
XCTAssertEqual(message, "API key not valid. Please pass a valid API key.")
253253
} catch {
254254
XCTFail("Should throw GenerateContentError.invalidAPIKey; error thrown: \(error)")
255255
}

0 commit comments

Comments
 (0)