errors.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package pgconn
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "regexp"
  9. "strings"
  10. )
  11. // SafeToRetry checks if the err is guaranteed to have occurred before sending any data to the server.
  12. func SafeToRetry(err error) bool {
  13. var retryableErr interface{ SafeToRetry() bool }
  14. if errors.As(err, &retryableErr) {
  15. return retryableErr.SafeToRetry()
  16. }
  17. return false
  18. }
  19. // Timeout checks if err was caused by a timeout. To be specific, it is true if err was caused within pgconn by a
  20. // context.DeadlineExceeded or an implementer of net.Error where Timeout() is true.
  21. func Timeout(err error) bool {
  22. var timeoutErr *errTimeout
  23. return errors.As(err, &timeoutErr)
  24. }
  25. // PgError represents an error reported by the PostgreSQL server. See
  26. // http://www.postgresql.org/docs/current/static/protocol-error-fields.html for
  27. // detailed field description.
  28. type PgError struct {
  29. Severity string
  30. SeverityUnlocalized string
  31. Code string
  32. Message string
  33. Detail string
  34. Hint string
  35. Position int32
  36. InternalPosition int32
  37. InternalQuery string
  38. Where string
  39. SchemaName string
  40. TableName string
  41. ColumnName string
  42. DataTypeName string
  43. ConstraintName string
  44. File string
  45. Line int32
  46. Routine string
  47. }
  48. func (pe *PgError) Error() string {
  49. return pe.Severity + ": " + pe.Message + " (SQLSTATE " + pe.Code + ")"
  50. }
  51. // SQLState returns the SQLState of the error.
  52. func (pe *PgError) SQLState() string {
  53. return pe.Code
  54. }
  55. // ConnectError is the error returned when a connection attempt fails.
  56. type ConnectError struct {
  57. Config *Config // The configuration that was used in the connection attempt.
  58. err error
  59. }
  60. func (e *ConnectError) Error() string {
  61. prefix := fmt.Sprintf("failed to connect to `user=%s database=%s`:", e.Config.User, e.Config.Database)
  62. details := e.err.Error()
  63. if strings.Contains(details, "\n") {
  64. return prefix + "\n\t" + strings.ReplaceAll(details, "\n", "\n\t")
  65. } else {
  66. return prefix + " " + details
  67. }
  68. }
  69. func (e *ConnectError) Unwrap() error {
  70. return e.err
  71. }
  72. type perDialConnectError struct {
  73. address string
  74. originalHostname string
  75. err error
  76. }
  77. func (e *perDialConnectError) Error() string {
  78. return fmt.Sprintf("%s (%s): %s", e.address, e.originalHostname, e.err.Error())
  79. }
  80. func (e *perDialConnectError) Unwrap() error {
  81. return e.err
  82. }
  83. type connLockError struct {
  84. status string
  85. }
  86. func (e *connLockError) SafeToRetry() bool {
  87. return true // a lock failure by definition happens before the connection is used.
  88. }
  89. func (e *connLockError) Error() string {
  90. return e.status
  91. }
  92. // ParseConfigError is the error returned when a connection string cannot be parsed.
  93. type ParseConfigError struct {
  94. ConnString string // The connection string that could not be parsed.
  95. msg string
  96. err error
  97. }
  98. func NewParseConfigError(conn, msg string, err error) error {
  99. return &ParseConfigError{
  100. ConnString: conn,
  101. msg: msg,
  102. err: err,
  103. }
  104. }
  105. func (e *ParseConfigError) Error() string {
  106. // Now that ParseConfigError is public and ConnString is available to the developer, perhaps it would be better only
  107. // return a static string. That would ensure that the error message cannot leak a password. The ConnString field would
  108. // allow access to the original string if desired and Unwrap would allow access to the underlying error.
  109. connString := redactPW(e.ConnString)
  110. if e.err == nil {
  111. return fmt.Sprintf("cannot parse `%s`: %s", connString, e.msg)
  112. }
  113. return fmt.Sprintf("cannot parse `%s`: %s (%s)", connString, e.msg, e.err.Error())
  114. }
  115. func (e *ParseConfigError) Unwrap() error {
  116. return e.err
  117. }
  118. func normalizeTimeoutError(ctx context.Context, err error) error {
  119. var netErr net.Error
  120. if errors.As(err, &netErr) && netErr.Timeout() {
  121. if ctx.Err() == context.Canceled {
  122. // Since the timeout was caused by a context cancellation, the actual error is context.Canceled not the timeout error.
  123. return context.Canceled
  124. } else if ctx.Err() == context.DeadlineExceeded {
  125. return &errTimeout{err: ctx.Err()}
  126. } else {
  127. return &errTimeout{err: netErr}
  128. }
  129. }
  130. return err
  131. }
  132. type pgconnError struct {
  133. msg string
  134. err error
  135. safeToRetry bool
  136. }
  137. func (e *pgconnError) Error() string {
  138. if e.msg == "" {
  139. return e.err.Error()
  140. }
  141. if e.err == nil {
  142. return e.msg
  143. }
  144. return fmt.Sprintf("%s: %s", e.msg, e.err.Error())
  145. }
  146. func (e *pgconnError) SafeToRetry() bool {
  147. return e.safeToRetry
  148. }
  149. func (e *pgconnError) Unwrap() error {
  150. return e.err
  151. }
  152. // errTimeout occurs when an error was caused by a timeout. Specifically, it wraps an error which is
  153. // context.Canceled, context.DeadlineExceeded, or an implementer of net.Error where Timeout() is true.
  154. type errTimeout struct {
  155. err error
  156. }
  157. func (e *errTimeout) Error() string {
  158. return fmt.Sprintf("timeout: %s", e.err.Error())
  159. }
  160. func (e *errTimeout) SafeToRetry() bool {
  161. return SafeToRetry(e.err)
  162. }
  163. func (e *errTimeout) Unwrap() error {
  164. return e.err
  165. }
  166. type contextAlreadyDoneError struct {
  167. err error
  168. }
  169. func (e *contextAlreadyDoneError) Error() string {
  170. return fmt.Sprintf("context already done: %s", e.err.Error())
  171. }
  172. func (e *contextAlreadyDoneError) SafeToRetry() bool {
  173. return true
  174. }
  175. func (e *contextAlreadyDoneError) Unwrap() error {
  176. return e.err
  177. }
  178. // newContextAlreadyDoneError double-wraps a context error in `contextAlreadyDoneError` and `errTimeout`.
  179. func newContextAlreadyDoneError(ctx context.Context) (err error) {
  180. return &errTimeout{&contextAlreadyDoneError{err: ctx.Err()}}
  181. }
  182. func redactPW(connString string) string {
  183. if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") {
  184. if u, err := url.Parse(connString); err == nil {
  185. return redactURL(u)
  186. }
  187. }
  188. quotedKV := regexp.MustCompile(`password='[^']*'`)
  189. connString = quotedKV.ReplaceAllLiteralString(connString, "password=xxxxx")
  190. plainKV := regexp.MustCompile(`password=[^ ]*`)
  191. connString = plainKV.ReplaceAllLiteralString(connString, "password=xxxxx")
  192. brokenURL := regexp.MustCompile(`:[^:@]+?@`)
  193. connString = brokenURL.ReplaceAllLiteralString(connString, ":xxxxxx@")
  194. return connString
  195. }
  196. func redactURL(u *url.URL) string {
  197. if u == nil {
  198. return ""
  199. }
  200. if _, pwSet := u.User.Password(); pwSet {
  201. u.User = url.UserPassword(u.User.Username(), "xxxxx")
  202. }
  203. return u.String()
  204. }
  205. type NotPreferredError struct {
  206. err error
  207. safeToRetry bool
  208. }
  209. func (e *NotPreferredError) Error() string {
  210. return fmt.Sprintf("standby server not found: %s", e.err.Error())
  211. }
  212. func (e *NotPreferredError) SafeToRetry() bool {
  213. return e.safeToRetry
  214. }
  215. func (e *NotPreferredError) Unwrap() error {
  216. return e.err
  217. }
  218. type PrepareError struct {
  219. err error
  220. ParseComplete bool // Indicates whether the error occurred after a ParseComplete message was received.
  221. }
  222. func (e *PrepareError) Error() string {
  223. if e.ParseComplete {
  224. return fmt.Sprintf("prepare failed after ParseComplete: %s", e.err.Error())
  225. }
  226. return e.err.Error()
  227. }
  228. func (e *PrepareError) Unwrap() error {
  229. return e.err
  230. }