package apperr import ( "errors" "fmt" "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 } if pgErr, ok := errors.AsType[*pgconn.PgError](e.err); ok { 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) }