fix(backend): dbErr 503 degradation for connection-class DB errors

This commit is contained in:
2026-09-06 19:53:19 +08:00
parent 04095b5438
commit a11bf28155
8 changed files with 61 additions and 18 deletions
+22
View File
@@ -1,10 +1,17 @@
package api
import (
"errors"
"io"
"log"
"net"
"net/http"
"strings"
"syscall"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/puddle/v2"
"booklib/internal/auth"
"booklib/internal/config"
@@ -24,6 +31,21 @@ func err(c *gin.Context, status int, code, msg string) {
c.AbortWithStatusJSON(status, gin.H{"error": gin.H{"code": code, "message": msg}})
}
// dbErr 统一处理 store 层失败:记日志;连接类错误 503(Service Unavailable),其余 500
// 注:brief 里的 pgxpool.ErrClosedPool 在 pgx v5 不存在,实际由 puddle 原样透出,用它替代;
// PG 停机时池内连接先收到 SQLSTATE 57P01(administrator shutdown),故把 08xx/57Pxx 也归为 503
func dbErr(c *gin.Context, e error) {
log.Printf("db: %v", e)
status, code := http.StatusInternalServerError, "internal"
var pgErr *pgconn.PgError
connClass := errors.As(e, &pgErr) && (strings.HasPrefix(pgErr.Code, "08") || strings.HasPrefix(pgErr.Code, "57P"))
if connClass || errors.Is(e, syscall.ECONNREFUSED) || errors.Is(e, io.ErrUnexpectedEOF) ||
errors.Is(e, net.ErrClosed) || errors.Is(e, puddle.ErrClosedPool) {
status, code = http.StatusServiceUnavailable, "unavailable"
}
err(c, status, code, "db error")
}
func (a *api) authMw() gin.HandlerFunc {
return func(c *gin.Context) {
h := c.GetHeader("Authorization")