Skip to content

Commit

Permalink
✨ Separate error cases clearer
Browse files Browse the repository at this point in the history
  • Loading branch information
lauvsong committed Apr 8, 2024
1 parent c659284 commit 13f6127
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@ data class ChatGptResponse(
code = choices.first().text.substringAfter("Code:").trim('`', '\n', ' ')
)
}

fun getFinishReason(): String {
return choices.first().finishReason
}
}
34 changes: 29 additions & 5 deletions src/main/kotlin/com/lauvsong/refactorgpt/service/ChatGptService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,38 @@ class ChatGptService(
onSuccess = { response -> onRefactorSuccess(response) },
onFailure = { exception ->
if (exception is SocketTimeoutException) {
throw ChatGptFetchFailureException("timeout error.\nPlease check your network or set longer timeout in settings.")
throw ChatGptFetchFailureException(
"""
timeout error.
Please check your network or set longer timeout in settings.
"""
)
}
throw ChatGptFetchFailureException(exception.message)
}
)

private fun onRefactorSuccess(response: Response<ChatGptResponse>): Refactored =
takeUnless { response.code() == 401 }
?.let { response.body()?.toRefactored() }
?: throw ChatGptAuthenticationException()
private fun onRefactorSuccess(response: Response<ChatGptResponse>): Refactored {
if (response.code() == 401) {
throw ChatGptAuthenticationException()
}

val body = response.body()
?: throw ChatGptFetchFailureException("OpenAI's response body is null.")

if (response.isSuccessful.not()) {
throw ChatGptFetchFailureException("${response.errorBody()?.string()}")
}

if (body.getFinishReason() == "length") {
throw ChatGptFetchFailureException(
"""
The response exceeds the maximum token limit.
Please try again with a shorter code.
"""
)
}

return body.toRefactored()
}
}

0 comments on commit 13f6127

Please sign in to comment.