Skip to content

Commit

Permalink
Add SQLState to MySQLError (#1321)
Browse files Browse the repository at this point in the history
Report SQLState in MySQLError to allow library users to distinguish user-defined from client / server errors.
  • Loading branch information
thopos committed Apr 13, 2022
1 parent eff3908 commit ad9fa14
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 10 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -110,6 +110,7 @@ Ziheng Lyu <zihenglv at gmail.com>
Barracuda Networks, Inc.
Counting Ltd.
DigitalOcean Inc.
dyves labs AG
Facebook Inc.
GitHub Inc.
Google Inc.
Expand Down
9 changes: 7 additions & 2 deletions errors.go
Expand Up @@ -56,11 +56,16 @@ func SetLogger(logger Logger) error {

// MySQLError is an error type which represents a single MySQL error
type MySQLError struct {
Number uint16
Message string
Number uint16
SQLState [5]byte
Message string
}

func (me *MySQLError) Error() string {
if me.SQLState != [5]byte{} {
return fmt.Sprintf("Error %d (%s): %s", me.Number, me.SQLState, me.Message)
}

return fmt.Sprintf("Error %d: %s", me.Number, me.Message)
}

Expand Down
6 changes: 3 additions & 3 deletions errors_test.go
Expand Up @@ -43,13 +43,13 @@ func TestErrorsStrictIgnoreNotes(t *testing.T) {
}

func TestMySQLErrIs(t *testing.T) {
infraErr := &MySQLError{1234, "the server is on fire"}
otherInfraErr := &MySQLError{1234, "the datacenter is flooded"}
infraErr := &MySQLError{Number: 1234, Message: "the server is on fire"}
otherInfraErr := &MySQLError{Number: 1234, Message: "the datacenter is flooded"}
if !errors.Is(infraErr, otherInfraErr) {
t.Errorf("expected errors to be the same: %+v %+v", infraErr, otherInfraErr)
}

differentCodeErr := &MySQLError{5678, "the server is on fire"}
differentCodeErr := &MySQLError{Number: 5678, Message: "the server is on fire"}
if errors.Is(infraErr, differentCodeErr) {
t.Fatalf("expected errors to be different: %+v %+v", infraErr, differentCodeErr)
}
Expand Down
11 changes: 6 additions & 5 deletions packets.go
Expand Up @@ -587,19 +587,20 @@ func (mc *mysqlConn) handleErrorPacket(data []byte) error {
return driver.ErrBadConn
}

me := &MySQLError{Number: errno}

pos := 3

// SQL State [optional: # + 5bytes string]
if data[3] == 0x23 {
//sqlstate := string(data[4 : 4+5])
copy(me.SQLState[:], data[4:4+5])
pos = 9
}

// Error Message [string]
return &MySQLError{
Number: errno,
Message: string(data[pos:]),
}
me.Message = string(data[pos:])

return me
}

func readStatus(b []byte) statusFlag {
Expand Down

0 comments on commit ad9fa14

Please sign in to comment.