Repository: sashabaranov/go-openai
Pull request #881 (2024-10-16 12:18:44)

Handling for non-json response
**Describe the change**
Since the original error response is included in the body field of openai.RequestError, even when the response is not in JSON format, it would be more appropriate to return openai.RequestError directly, rather than returning an errorString. This approach ensures that the original error details are preserved within the body field.

**Describe your solution**
Removed the condition that checked if the response was in a non-JSON format and returned an errorString with the original error response. Now, the original error response will be directly included in the body field of openai.RequestError.



codecov[bot]: ## [Codecov](https://app.codecov.io/gh/sashabaranov/go-openai/pull/881?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Alex+Baranov) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 99.04%. Comparing base [(`774fc9d`)](https://app.codecov.io/gh/sashabaranov/go-openai/commit/774fc9dd12ed60c10a9f9f03319ddb9cd5f8780c?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Alex+Baranov) to head [(`22cf414`)](https://app.codecov.io/gh/sashabaranov/go-openai/commit/22cf414b4be89a38eb702b13c27be1de6bcef74d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Alex+Baranov).
> Report is 64 commits behind head on master.

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##           master     #881      +/-   ##
==========================================
+ Coverage   98.46%   99.04%   +0.58%     
==========================================
  Files          24       26       +2     
  Lines        1364     1460      +96     
==========================================
+ Hits         1343     1446     +103     
+ Misses         15        8       -7     
  Partials        6        6              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/sashabaranov/go-openai/pull/881?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Alex+Baranov).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Alex+Baranov).

AyushSawant18588: @sashabaranov Can you please look into this?
sashabaranov: Thank you for the PR!
johnugeorge: Thanks @sashabaranov. Can you please review this again?

Patch:
diff --git a/client.go b/client.go
index 1e228a0..ed8595e 100644
--- a/client.go
+++ b/client.go
@@ -289,9 +289,6 @@ func (c *Client) handleErrorResp(resp *http.Response) error {
 	if err != nil {
 		return fmt.Errorf("error, reading response body: %w", err)
 	}
-	if !strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
-		return fmt.Errorf("error, status code: %d, status: %s, body: %s", resp.StatusCode, resp.Status, body)
-	}
 	var errRes ErrorResponse
 	err = json.Unmarshal(body, &errRes)
 	if err != nil || errRes.Error == nil {
diff --git a/error.go b/error.go
index fc9e7cd..8a74bd5 100644
--- a/error.go
+++ b/error.go
@@ -104,7 +104,10 @@ func (e *APIError) UnmarshalJSON(data []byte) (err error) {
 }
 
 func (e *RequestError) Error() string {
-	return fmt.Sprintf("error, status code: %d, status: %s, message: %s", e.HTTPStatusCode, e.HTTPStatus, e.Err)
+	return fmt.Sprintf(
+		"error, status code: %d, status: %s, message: %s, body: %s",
+		e.HTTPStatusCode, e.HTTPStatus, e.Err, e.Body,
+	)
 }
 
 func (e *RequestError) Unwrap() error {


Test patch:
diff --git a/client_test.go b/client_test.go
index 18da787..354a6b3 100644
--- a/client_test.go
+++ b/client_test.go
@@ -194,26 +194,31 @@ func TestHandleErrorResp(t *testing.T) {
 				{
 					"error":{}
 				}`)),
-			expected: "error, status code: 503, status: , message: ",
+			expected: `error, status code: 503, status: , message: , body: 
+				{
+					"error":{}
+				}`,
 		},
 		{
 			name:        "413 Request Entity Too Large",
 			httpCode:    http.StatusRequestEntityTooLarge,
 			contentType: "text/html",
-			body: bytes.NewReader([]byte(`<html>
-<head><title>413 Request Entity Too Large</title></head>
-<body>
-<center><h1>413 Request Entity Too Large</h1></center>
-<hr><center>nginx</center>
-</body>
-</html>`)),
-			expected: `error, status code: 413, status: , body: <html>
-<head><title>413 Request Entity Too Large</title></head>
-<body>
-<center><h1>413 Request Entity Too Large</h1></center>
-<hr><center>nginx</center>
-</body>
-</html>`,
+			body: bytes.NewReader([]byte(`
+	<html>
+	<head><title>413 Request Entity Too Large</title></head>
+	<body>
+	<center><h1>413 Request Entity Too Large</h1></center>
+	<hr><center>nginx</center>
+	</body>
+	</html>`)),
+			expected: `error, status code: 413, status: , message: invalid character '<' looking for beginning of value, body: 
+	<html>
+	<head><title>413 Request Entity Too Large</title></head>
+	<body>
+	<center><h1>413 Request Entity Too Large</h1></center>
+	<hr><center>nginx</center>
+	</body>
+	</html>`,
 		},
 		{
 			name:        "errorReader",