autoresearch iter 3: share upload-record error mapping via filesrv helper

ServeFileByID and DownloadFile duplicated the lookup failure mapping and
each used an unchecked *strconv.NumError assertion that cannot match a
wrapped error. One helper now classifies 404 vs 400 via errors.As; each
endpoint keeps its own fallback for unclassified failures. ErrInvalidUploadID
became unused once both sites report ErrInvalidFileID for a malformed ID.
This commit is contained in:
ryan
2026-08-29 08:02:42 +08:00
parent 4e6209bf61
commit 686e3ef5a6
3 changed files with 19 additions and 13 deletions
@@ -76,12 +76,7 @@ const (
func ServeFileByID(c *gin.Context) {
upload, err := GetUploadRecordByID(c)
if err != nil {
if repository.IsRecordNotFound(err) {
response.AbortNotFound(c, shared.ErrFileRecordNotFound)
return
}
if _, ok := err.(*strconv.NumError); ok {
response.AbortBadRequest(c, shared.ErrInvalidUploadID)
if AbortUploadRecordError(c, err) {
return
}
response.AbortInternal(c, shared.ErrInternalServerError)
@@ -96,6 +91,23 @@ func ServeFileByID(c *gin.Context) {
ServeUpload(c, upload)
}
// AbortUploadRecordError maps an upload record lookup failure to its HTTP
// response and reports whether it handled the error. A missing record is 404
// and a malformed path ID is 400; anything else is left to the caller.
func AbortUploadRecordError(c *gin.Context, err error) bool {
var numErr *strconv.NumError
switch {
case repository.IsRecordNotFound(err):
response.AbortNotFound(c, shared.ErrFileRecordNotFound)
return true
case errors.As(err, &numErr):
response.AbortBadRequest(c, shared.ErrInvalidFileID)
return true
default:
return false
}
}
// GetUploadRecordByID 从请求路径参数中解析文件 ID 并从数据库中检索处于 Pending 或 Used 状态的上传记录。
func GetUploadRecordByID(c *gin.Context) (*models.Upload, error) {
c.Header("X-Content-Type-Options", "nosniff")
@@ -169,12 +169,7 @@ func UploadFile(c *gin.Context) {
func DownloadFile(c *gin.Context) {
upload, err := filesrv.GetUploadRecordByID(c)
if err != nil {
if isRecordNotFound(err) {
response.AbortNotFound(c, shared.ErrFileRecordNotFound)
return
}
if _, ok := err.(*strconv.NumError); ok {
response.AbortBadRequest(c, shared.ErrInvalidFileID)
if filesrv.AbortUploadRecordError(c, err) {
return
}
response.AbortBadRequest(c, shared.ErrQueryUploadRecordFailed)
@@ -43,7 +43,6 @@ const (
ErrFileRecordNotFound = "文件记录未找到"
ErrFileNotFound = "文件未找到"
ErrOperationForbidden = "无权操作"
ErrInvalidUploadID = "无效的上传ID"
ErrInvalidAccessModeParam = "无效的 access_mode 参数"
ErrInternalServerError = "服务器内部错误"
)