github.com/pingcap/tidb/parser@v0.0.0-20231013125129-93a834a6bf8d/mysql/error.go (about) 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 14 package mysql 15 16 import ( 17 "fmt" 18 19 "github.com/pingcap/errors" 20 ) 21 22 // Portable analogs of some common call errors. 23 var ( 24 ErrBadConn = errors.New("connection was bad") 25 ErrMalformPacket = errors.New("malform packet error") 26 ) 27 28 // SQLError records an error information, from executing SQL. 29 type SQLError struct { 30 Code uint16 31 Message string 32 State string 33 } 34 35 // Error prints errors, with a formatted string. 36 func (e *SQLError) Error() string { 37 return fmt.Sprintf("ERROR %d (%s): %s", e.Code, e.State, e.Message) 38 } 39 40 // NewErr generates a SQL error, with an error code and default format specifier defined in MySQLErrName. 41 func NewErr(errCode uint16, args ...interface{}) *SQLError { 42 e := &SQLError{Code: errCode} 43 44 if s, ok := MySQLState[errCode]; ok { 45 e.State = s 46 } else { 47 e.State = DefaultMySQLState 48 } 49 50 if sqlErr, ok := MySQLErrName[errCode]; ok { 51 errors.RedactErrorArg(args, sqlErr.RedactArgPos) 52 e.Message = fmt.Sprintf(sqlErr.Raw, args...) 53 } else { 54 e.Message = fmt.Sprint(args...) 55 } 56 57 return e 58 } 59 60 // NewErrf creates a SQL error, with an error code and a format specifier. 61 func NewErrf(errCode uint16, format string, redactArgPos []int, args ...interface{}) *SQLError { 62 e := &SQLError{Code: errCode} 63 64 if s, ok := MySQLState[errCode]; ok { 65 e.State = s 66 } else { 67 e.State = DefaultMySQLState 68 } 69 70 errors.RedactErrorArg(args, redactArgPos) 71 e.Message = fmt.Sprintf(format, args...) 72 73 return e 74 }