fix(api): classify DB errors in library paths

This commit is contained in:
2026-09-07 12:44:47 +08:00
parent 12f6e82308
commit 93638ed647
2 changed files with 23 additions and 5 deletions
+14 -2
View File
@@ -42,9 +42,13 @@ func (a *api) bookFromParam(c *gin.Context) (store.Book, bool) {
func (a *api) getLibRow(c *gin.Context, id int64) (store.Library, bool) { func (a *api) getLibRow(c *gin.Context, id int64) (store.Library, bool) {
l, e := a.st.GetLibrary(c, id) l, e := a.st.GetLibrary(c, id)
if e != nil { if e != nil {
if errors.Is(e, pgx.ErrNoRows) {
err(c, http.StatusNotFound, "not_found", "no such library") err(c, http.StatusNotFound, "not_found", "no such library")
return store.Library{}, false return store.Library{}, false
} }
dbErr(c, e)
return store.Library{}, false
}
return l, true return l, true
} }
@@ -102,8 +106,16 @@ func (a *api) getBook(c *gin.Context) {
if !ok { if !ok {
return return
} }
p, _ := a.st.GetProgress(c, uid(c), b.LibraryID, b.Path) // ErrNoRows → 零值 percent p, e := a.st.GetProgress(c, uid(c), b.LibraryID, b.Path) // ErrNoRows → 零值 percent
lib, _ := a.st.GetLibrary(c, b.LibraryID) if e != nil && !errors.Is(e, pgx.ErrNoRows) {
dbErr(c, e)
return
}
lib, e := a.st.GetLibrary(c, b.LibraryID)
if e != nil && !errors.Is(e, pgx.ErrNoRows) { // 库被并发删则留空 library 名,书仍可见
dbErr(c, e)
return
}
c.JSON(http.StatusOK, bookJSON(b, p.Percent, lib.Name)) c.JSON(http.StatusOK, bookJSON(b, p.Percent, lib.Name))
} }
+7 -1
View File
@@ -2,6 +2,7 @@ package api
import ( import (
"context" "context"
"errors"
"io" "io"
"net/http" "net/http"
"os" "os"
@@ -11,6 +12,7 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"booklib/internal/bookfile" "booklib/internal/bookfile"
"booklib/internal/store" "booklib/internal/store"
@@ -60,7 +62,7 @@ func (a *api) createLibrary(c *gin.Context) {
err(c, http.StatusConflict, "exists", "root_path taken") err(c, http.StatusConflict, "exists", "root_path taken")
return return
} }
err(c, http.StatusBadRequest, "bad_request", "invalid input") dbErr(c, e)
return return
} }
c.JSON(http.StatusCreated, gin.H{"id": id, "name": req.Name, "root_path": filepath.Clean(req.RootPath)}) c.JSON(http.StatusCreated, gin.H{"id": id, "name": req.Name, "root_path": filepath.Clean(req.RootPath)})
@@ -74,9 +76,13 @@ func (a *api) getLibrary(c *gin.Context) (store.Library, bool) {
} }
lib, e := a.st.GetLibrary(c, id) lib, e := a.st.GetLibrary(c, id)
if e != nil { if e != nil {
if errors.Is(e, pgx.ErrNoRows) {
err(c, http.StatusNotFound, "not_found", "no such library") err(c, http.StatusNotFound, "not_found", "no such library")
return store.Library{}, false return store.Library{}, false
} }
dbErr(c, e)
return store.Library{}, false
}
return lib, true return lib, true
} }