forked from mtusi2026/mtusi2026lab6
Реализация на 5
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func WrapPostgres(err error, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
code: CodeInternal,
|
||||
meta: metadata{},
|
||||
}
|
||||
|
||||
m.handlePostgres()
|
||||
|
||||
return &m
|
||||
}
|
||||
|
||||
func (e *AppError) handlePostgres() {
|
||||
if e.err == nil {
|
||||
e.code = CodeOK
|
||||
return
|
||||
}
|
||||
|
||||
var networkError net.Error
|
||||
var connectError *pgconn.ConnectError
|
||||
if errors.Is(e.err, context.DeadlineExceeded) || errors.Is(e.err, io.EOF) ||
|
||||
errors.Is(e.err, io.ErrUnexpectedEOF) || errors.As(e.err, &networkError) || errors.As(e.err, &connectError) {
|
||||
e.code = CodeServiceUnavailable
|
||||
e.msg = "database unavailable"
|
||||
return
|
||||
}
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](e.err); ok {
|
||||
if strings.HasPrefix(pgErr.Code, "08") || pgErr.Code == "57014" ||
|
||||
pgErr.Code == "57P01" || pgErr.Code == "57P02" || pgErr.Code == "57P03" || pgErr.Code == "53300" {
|
||||
e.code = CodeServiceUnavailable
|
||||
e.msg = "database unavailable"
|
||||
return
|
||||
}
|
||||
e.meta[PgErrorCode] = pgErr.Code
|
||||
e.code = CodeFromPostgres(pgErr.Code)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case errors.Is(e.err, pgx.ErrNoRows):
|
||||
e.msg = fmt.Sprintf("not found: %s", e.msg)
|
||||
e.code = CodeNotFound
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTooManyRows):
|
||||
e.msg = fmt.Sprintf("got too many rows: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTxClosed):
|
||||
e.msg = fmt.Sprintf("transaction is closed: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTxCommitRollback):
|
||||
e.msg = fmt.Sprintf("transaction commit resulted in rollback: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (e *AppError) PgCode() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
if e.meta == nil {
|
||||
return ""
|
||||
}
|
||||
return e.meta.Get(PgErrorCode)
|
||||
}
|
||||
Reference in New Issue
Block a user