mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-10-28 16:46:57 +08:00
A failed read consumes and closes the request body. Endpoints that read it a second time then answered "http: invalid Read on closed Body" instead of the cause: /v1/video/generations, and audio transcriptions and translations. The first failure is now kept for the rest of the request, so every later reader reports it. A body over MAX_REQUEST_BODY_MB now gets 413 instead of 400 on the endpoints that still answered 400: ordinary relay endpoints such as /v1/chat/completions, Midjourney, task plugin routes and /v1/tasks. Task plugin routes also write the cause to the log, and Midjourney errors no longer repeat "Invalid request:".
56 lines
1.6 KiB
Go
56 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/dto"
|
|
"github.com/QuantumNous/new-api/logger"
|
|
pluginruntime "github.com/QuantumNous/new-api/pkg/jsplugin"
|
|
"github.com/QuantumNous/new-api/relaykit/types"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func abortWithOpenAiMessage(c *gin.Context, statusCode int, message string, code ...types.ErrorCode) {
|
|
codeStr := ""
|
|
if len(code) > 0 {
|
|
codeStr = string(code[0])
|
|
}
|
|
userId := c.GetInt("id")
|
|
_, preparedPluginRoute := c.Get(pluginruntime.ContextKeyRouteRequest)
|
|
if !preparedPluginRoute || !RespondTaskPluginError(c, &dto.TaskError{
|
|
Code: codeStr,
|
|
Message: message,
|
|
StatusCode: statusCode,
|
|
}) {
|
|
c.JSON(statusCode, gin.H{
|
|
"error": gin.H{
|
|
"message": common.MessageWithRequestId(message, c.GetString(common.RequestIdKey)),
|
|
"type": "new_api_error",
|
|
"code": codeStr,
|
|
},
|
|
})
|
|
}
|
|
c.Abort()
|
|
logger.LogError(c.Request.Context(), common.LogText("user %d | %s", userId, message))
|
|
}
|
|
|
|
// invalidRequestStatus is the status of a request whose body could not be
|
|
// read or parsed: 413 when the body exceeds MAX_REQUEST_BODY_MB, else 400.
|
|
func invalidRequestStatus(err error) int {
|
|
if common.IsRequestBodyTooLargeError(err) {
|
|
return http.StatusRequestEntityTooLarge
|
|
}
|
|
return http.StatusBadRequest
|
|
}
|
|
|
|
func abortWithMidjourneyMessage(c *gin.Context, statusCode int, code int, description string) {
|
|
c.JSON(statusCode, gin.H{
|
|
"description": description,
|
|
"type": "new_api_error",
|
|
"code": code,
|
|
})
|
|
c.Abort()
|
|
logger.LogError(c.Request.Context(), description)
|
|
}
|