Skip to content

Commit

Permalink
support Is comparison on MySQLError (#1210)
Browse files Browse the repository at this point in the history
* support Is comparison on MySQLError

* add myself to authors

* skip error tests for go 1.12

* remove test build tag
  • Loading branch information
chriskirkland committed Jun 3, 2021
1 parent e74ba5c commit 417641a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -23,6 +23,7 @@ Asta Xie <xiemengjun at gmail.com>
Bulat Gaifullin <gaifullinbf at gmail.com>
Caine Jette <jette at alum.mit.edu>
Carlos Nieto <jose.carlos at menteslibres.net>
Chris Kirkland <chriskirkland at github.com>
Chris Moos <chris at tech9computers.com>
Craig Wilson <craiggwilson at gmail.com>
Daniel Montoya <dsmontoyam at gmail.com>
Expand Down
7 changes: 7 additions & 0 deletions errors.go
Expand Up @@ -63,3 +63,10 @@ type MySQLError struct {
func (me *MySQLError) Error() string {
return fmt.Sprintf("Error %d: %s", me.Number, me.Message)
}

func (me *MySQLError) Is(err error) bool {
if merr, ok := err.(*MySQLError); ok {
return merr.Number == me.Number
}
return false
}
19 changes: 19 additions & 0 deletions errors_test.go
Expand Up @@ -10,6 +10,7 @@ package mysql

import (
"bytes"
"errors"
"log"
"testing"
)
Expand Down Expand Up @@ -40,3 +41,21 @@ func TestErrorsStrictIgnoreNotes(t *testing.T) {
dbt.mustExec("DROP TABLE IF EXISTS does_not_exist")
})
}

func TestMySQLErrIs(t *testing.T) {
infraErr := &MySQLError{1234, "the server is on fire"}
otherInfraErr := &MySQLError{1234, "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"}
if errors.Is(infraErr, differentCodeErr) {
t.Fatalf("expected errors to be different: %+v %+v", infraErr, differentCodeErr)
}

nonMysqlErr := errors.New("not a mysql error")
if errors.Is(infraErr, nonMysqlErr) {
t.Fatalf("expected errors to be different: %+v %+v", infraErr, nonMysqlErr)
}
}

0 comments on commit 417641a

Please sign in to comment.