fix(api): classify DB errors in library paths
This commit is contained in:
@@ -42,7 +42,11 @@ func (a *api) bookFromParam(c *gin.Context) (store.Book, bool) {
|
||||
func (a *api) getLibRow(c *gin.Context, id int64) (store.Library, bool) {
|
||||
l, e := a.st.GetLibrary(c, id)
|
||||
if e != nil {
|
||||
err(c, http.StatusNotFound, "not_found", "no such library")
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
err(c, http.StatusNotFound, "not_found", "no such library")
|
||||
return store.Library{}, false
|
||||
}
|
||||
dbErr(c, e)
|
||||
return store.Library{}, false
|
||||
}
|
||||
return l, true
|
||||
@@ -102,8 +106,16 @@ func (a *api) getBook(c *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
p, _ := a.st.GetProgress(c, uid(c), b.LibraryID, b.Path) // ErrNoRows → 零值 percent
|
||||
lib, _ := a.st.GetLibrary(c, b.LibraryID)
|
||||
p, e := a.st.GetProgress(c, uid(c), b.LibraryID, b.Path) // ErrNoRows → 零值 percent
|
||||
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))
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"booklib/internal/bookfile"
|
||||
"booklib/internal/store"
|
||||
@@ -60,7 +62,7 @@ func (a *api) createLibrary(c *gin.Context) {
|
||||
err(c, http.StatusConflict, "exists", "root_path taken")
|
||||
return
|
||||
}
|
||||
err(c, http.StatusBadRequest, "bad_request", "invalid input")
|
||||
dbErr(c, e)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"id": id, "name": req.Name, "root_path": filepath.Clean(req.RootPath)})
|
||||
@@ -74,7 +76,11 @@ func (a *api) getLibrary(c *gin.Context) (store.Library, bool) {
|
||||
}
|
||||
lib, e := a.st.GetLibrary(c, id)
|
||||
if e != nil {
|
||||
err(c, http.StatusNotFound, "not_found", "no such library")
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
err(c, http.StatusNotFound, "not_found", "no such library")
|
||||
return store.Library{}, false
|
||||
}
|
||||
dbErr(c, e)
|
||||
return store.Library{}, false
|
||||
}
|
||||
return lib, true
|
||||
|
||||
Reference in New Issue
Block a user