From 417641ad42910e50863a0caf4740ce319262f2f9 Mon Sep 17 00:00:00 2001 From: Chris Kirkland Date: Thu, 3 Jun 2021 18:34:57 -0500 Subject: [PATCH] support Is comparison on MySQLError (#1210) * support Is comparison on MySQLError * add myself to authors * skip error tests for go 1.12 * remove test build tag --- AUTHORS | 1 + errors.go | 7 +++++++ errors_test.go | 19 +++++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/AUTHORS b/AUTHORS index 900dfec06..e3370e025 100644 --- a/AUTHORS +++ b/AUTHORS @@ -23,6 +23,7 @@ Asta Xie Bulat Gaifullin Caine Jette Carlos Nieto +Chris Kirkland Chris Moos Craig Wilson Daniel Montoya diff --git a/errors.go b/errors.go index 760782ff2..92cc9a361 100644 --- a/errors.go +++ b/errors.go @@ -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 +} diff --git a/errors_test.go b/errors_test.go index 96f9126d6..3a1aef74d 100644 --- a/errors_test.go +++ b/errors_test.go @@ -10,6 +10,7 @@ package mysql import ( "bytes" + "errors" "log" "testing" ) @@ -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) + } +}