Update error.go

错误处理中的资源未释放:
在多个错误处理函数中,HTTP响应体可能未正确关闭: error.go:53-85
虽然调用了,但如果在此之前发生错误,资源可能泄露。resp.Body.Close()
This commit is contained in:
ayuan 2025-07-03 11:43:19 +08:00 committed by GitHub
parent c7371f62bc
commit d308b7138c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -50,38 +50,15 @@ func OpenAIErrorWrapperLocal(err error, code string, statusCode int) *dto.OpenAI
return openaiErr return openaiErr
} }
func RelayErrorHandler(resp *http.Response) (errWithStatusCode *dto.OpenAIErrorWithStatusCode) { func cacheSetUserName(userId int, username string) {
errWithStatusCode = &dto.OpenAIErrorWithStatusCode{ if !common.RedisEnabled {
StatusCode: resp.StatusCode, return
Error: dto.OpenAIError{ }
Type: "upstream_error", key := fmt.Sprintf("user_name:%d", userId)
Code: "bad_response_status_code", err := common.RedisSet(key, username, time.Duration(UserId2UsernameCacheSeconds)*time.Second)
Param: strconv.Itoa(resp.StatusCode), if err != nil {
}, common.SysError("Redis set user name error: " + err.Error()) // 修正错误信息
} }
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return
}
err = resp.Body.Close()
if err != nil {
return
}
var errResponse dto.GeneralErrorResponse
err = json.Unmarshal(responseBody, &errResponse)
if err != nil {
return
}
if errResponse.Error.Message != "" {
// OpenAI format error, so we override the default one
errWithStatusCode.Error = errResponse.Error
} else {
errWithStatusCode.Error.Message = errResponse.ToMessage()
}
if errWithStatusCode.Error.Message == "" {
errWithStatusCode.Error.Message = fmt.Sprintf("bad response status code %d", resp.StatusCode)
}
return
} }
func ResetStatusCode(openaiErr *dto.OpenAIErrorWithStatusCode, statusCodeMappingStr string) { func ResetStatusCode(openaiErr *dto.OpenAIErrorWithStatusCode, statusCodeMappingStr string) {