diff --git a/error.go b/error.go index e60288a6..7343788b 100644 --- a/error.go +++ b/error.go @@ -3,6 +3,7 @@ package mssql import ( "database/sql/driver" "fmt" + "strings" ) // Error represents an SQL Server error. This @@ -24,7 +25,18 @@ type Error struct { } func (e Error) Error() string { - return "mssql: " + e.Message + errChain := e.All + if len(errChain) == 0 { + errChain = []Error{e} + } + var msg strings.Builder + for i, err := range errChain { + if i > 0 { + msg.WriteByte('\n') + } + fmt.Fprintf(&msg, "mssql: %s (%d)", err.Message, err.Number) + } + return msg.String() } func (e Error) String() string { diff --git a/queries_test.go b/queries_test.go index 00906587..cf042649 100644 --- a/queries_test.go +++ b/queries_test.go @@ -734,6 +734,19 @@ func TestError(t *testing.T) { if sqlerr.Number != 2812 { // Could not find stored procedure 'bad' t.Fatalf("Should be specific error code 2812, actually %d %s", sqlerr.Number, sqlerr) } + if len(sqlerr.All) != 1 { + t.Fatalf("Should have one error, actually %d: %+v", len(sqlerr.All), sqlerr.All) + } + if sqlerr.Number != sqlerr.All[0].Number { + t.Fatalf("Should have the same error number, actually %d and %d", sqlerr.Number, sqlerr.All[0].Number) + } + + // Error() reports one and only error in the list, in this case: + // "mssql: Could not find stored procedure 'bad'. (2812)" + expectedErrorText := fmt.Sprintf("mssql: %s (%d)", sqlerr.Message, sqlerr.Number) + if err.Error() != expectedErrorText { + t.Fatalf("Expected error text '%s', got '%s'", expectedErrorText, err.Error()) + } } } @@ -768,6 +781,19 @@ func TestMultipleErrors(t *testing.T) { if sqlerr.All[0].Number != 8111 { // Cannot define PRIMARY KEY constraint on nullable column in table t.Fatalf("Should be specific error code 8111, actually %d %s", sqlerr.All[0].Number, sqlerr.All[0]) } + + // Error() reports all error messages in the same order as + // they are reported by tools like sqlcmd (first to last): + // mssql: Cannot define PRIMARY KEY constraint on nullable column in table '#bad'. (8111) + // mssql: Could not create constraint or index. See previous errors. (1750) + expectedErrorText := fmt.Sprintf( + "mssql: %s (%d)\nmssql: %s (%d)", + sqlerr.All[0].Message, sqlerr.All[0].Number, + sqlerr.All[1].Message, sqlerr.All[1].Number, + ) + if err.Error() != expectedErrorText { + t.Fatalf("Expected error text '%s', got '%s'", expectedErrorText, err.Error()) + } } }