error.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2015 PingCAP, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package mysql
  14. import (
  15. "fmt"
  16. "github.com/pingcap/errors"
  17. )
  18. // Portable analogs of some common call errors.
  19. var (
  20. ErrBadConn = errors.New("connection was bad")
  21. ErrMalformPacket = errors.New("malform packet error")
  22. )
  23. // SQLError records an error information, from executing SQL.
  24. type SQLError struct {
  25. Code uint16
  26. Message string
  27. State string
  28. }
  29. // Error prints errors, with a formatted string.
  30. func (e *SQLError) Error() string {
  31. return fmt.Sprintf("ERROR %d (%s): %s", e.Code, e.State, e.Message)
  32. }
  33. // NewErr generates a SQL error, with an error code and default format specifier defined in MySQLErrName.
  34. func NewErr(errCode uint16, args ...interface{}) *SQLError {
  35. e := &SQLError{Code: errCode}
  36. if s, ok := MySQLState[errCode]; ok {
  37. e.State = s
  38. } else {
  39. e.State = DefaultMySQLState
  40. }
  41. if sqlErr, ok := MySQLErrName[errCode]; ok {
  42. errors.RedactErrorArg(args, sqlErr.RedactArgPos)
  43. e.Message = fmt.Sprintf(sqlErr.Raw, args...)
  44. } else {
  45. e.Message = fmt.Sprint(args...)
  46. }
  47. return e
  48. }
  49. // NewErrf creates a SQL error, with an error code and a format specifier.
  50. func NewErrf(errCode uint16, format string, redactArgPos []int, args ...interface{}) *SQLError {
  51. e := &SQLError{Code: errCode}
  52. if s, ok := MySQLState[errCode]; ok {
  53. e.State = s
  54. } else {
  55. e.State = DefaultMySQLState
  56. }
  57. errors.RedactErrorArg(args, redactArgPos)
  58. e.Message = fmt.Sprintf(format, args...)
  59. return e
  60. }