Skip to content

Commit 4ab8a7a

Browse files
committed
report SQLState in MySQLError
to allow library users to distinguish user-defined from client / server errors
1 parent a0b5ef3 commit 4ab8a7a

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

errors.go

+13-2
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,15 @@ func SetLogger(logger Logger) error {
5656

5757
// MySQLError is an error type which represents a single MySQL error
5858
type MySQLError struct {
59-
Number uint16
60-
Message string
59+
Number uint16
60+
SQLState string
61+
Message string
6162
}
6263

6364
func (me *MySQLError) Error() string {
65+
if me.SQLState != "" {
66+
return fmt.Sprintf("Error %d (%s): %s", me.Number, me.SQLState, me.Message)
67+
}
6468
return fmt.Sprintf("Error %d: %s", me.Number, me.Message)
6569
}
6670

@@ -70,3 +74,10 @@ func (me *MySQLError) Is(err error) bool {
7074
}
7175
return false
7276
}
77+
78+
func (me *MySQLError) IsWithSQLState(err error) bool {
79+
if merr, ok := err.(*MySQLError); ok {
80+
return merr.Number == me.Number && merr.SQLState == me.SQLState
81+
}
82+
return false
83+
}

errors_test.go

+16-3
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,13 @@ func TestErrorsStrictIgnoreNotes(t *testing.T) {
4343
}
4444

4545
func TestMySQLErrIs(t *testing.T) {
46-
infraErr := &MySQLError{1234, "the server is on fire"}
47-
otherInfraErr := &MySQLError{1234, "the datacenter is flooded"}
46+
infraErr := &MySQLError{1234, "", "the server is on fire"}
47+
otherInfraErr := &MySQLError{1234, "", "the datacenter is flooded"}
4848
if !errors.Is(infraErr, otherInfraErr) {
4949
t.Errorf("expected errors to be the same: %+v %+v", infraErr, otherInfraErr)
5050
}
5151

52-
differentCodeErr := &MySQLError{5678, "the server is on fire"}
52+
differentCodeErr := &MySQLError{5678, "", "the server is on fire"}
5353
if errors.Is(infraErr, differentCodeErr) {
5454
t.Fatalf("expected errors to be different: %+v %+v", infraErr, differentCodeErr)
5555
}
@@ -59,3 +59,16 @@ func TestMySQLErrIs(t *testing.T) {
5959
t.Fatalf("expected errors to be different: %+v %+v", infraErr, nonMysqlErr)
6060
}
6161
}
62+
63+
func TestMySQLErrIsWithSQLState(t *testing.T) {
64+
infraErr := &MySQLError{1234, "HY000", "the server is on fire"}
65+
otherInfraErr := &MySQLError{1234, "HY000", "the datacenter is flooded"}
66+
if !infraErr.IsWithSQLState(otherInfraErr) {
67+
t.Errorf("expected errors to be the same: %+v %+v", infraErr, otherInfraErr)
68+
}
69+
70+
differentCodeErr := &MySQLError{1234, "42000", "the server is on fire"}
71+
if infraErr.IsWithSQLState(differentCodeErr) {
72+
t.Fatalf("expected errors to be different: %+v %+v", infraErr, differentCodeErr)
73+
}
74+
}

0 commit comments

Comments
 (0)