Browse Source

fix: fix error response (close #468)

JustSong 2 years ago
parent
commit
a3e267df7e
2 changed files with 31 additions and 2 deletions
  1. 1 2
      controller/relay-text.go
  2. 30 0
      controller/relay-utils.go

+ 1 - 2
controller/relay-text.go

@@ -317,8 +317,7 @@ func relayTextHelper(c *gin.Context, relayMode int) *OpenAIErrorWithStatusCode {
 		isStream = isStream || strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream")
 
 		if resp.StatusCode != http.StatusOK {
-			return errorWrapper(
-				fmt.Errorf("bad status code: %d", resp.StatusCode), "bad_status_code", resp.StatusCode)
+			return relayErrorHandler(resp)
 		}
 	}
 

+ 30 - 0
controller/relay-utils.go

@@ -1,11 +1,14 @@
 package controller
 
 import (
+	"encoding/json"
 	"fmt"
 	"github.com/gin-gonic/gin"
 	"github.com/pkoukk/tiktoken-go"
+	"io"
 	"net/http"
 	"one-api/common"
+	"strconv"
 )
 
 var stopFinishReason = "stop"
@@ -119,3 +122,30 @@ func setEventStreamHeaders(c *gin.Context) {
 	c.Writer.Header().Set("Transfer-Encoding", "chunked")
 	c.Writer.Header().Set("X-Accel-Buffering", "no")
 }
+
+func relayErrorHandler(resp *http.Response) (openAIErrorWithStatusCode *OpenAIErrorWithStatusCode) {
+	openAIErrorWithStatusCode = &OpenAIErrorWithStatusCode{
+		StatusCode: resp.StatusCode,
+		OpenAIError: OpenAIError{
+			Message: fmt.Sprintf("bad response status code %d", resp.StatusCode),
+			Type:    "one_api_error",
+			Code:    "bad_response_status_code",
+			Param:   strconv.Itoa(resp.StatusCode),
+		},
+	}
+	responseBody, err := io.ReadAll(resp.Body)
+	if err != nil {
+		return
+	}
+	err = resp.Body.Close()
+	if err != nil {
+		return
+	}
+	var textResponse TextResponse
+	err = json.Unmarshal(responseBody, &textResponse)
+	if err != nil {
+		return
+	}
+	openAIErrorWithStatusCode.OpenAIError = textResponse.Error
+	return
+}