@@ -65,3 +65,52 @@ func TestAggregateSecondaryPreferredReadPreference(t *testing.T) {
65
65
assert .NotNil (mt , err , "expected command %s to not contain $readPreference" , evt .Command )
66
66
})
67
67
}
68
+
69
+ func TestErrorsCodeNamePropagated (t * testing.T ) {
70
+ // Ensure the codeName field is propagated for both command and write concern errors.
71
+
72
+ mtOpts := mtest .NewOptions ().
73
+ Topologies (mtest .ReplicaSet ).
74
+ CreateClient (false )
75
+ mt := mtest .New (t , mtOpts )
76
+ defer mt .Close ()
77
+
78
+ mt .RunOpts ("command error" , mtest .NewOptions ().MinServerVersion ("3.4" ), func (mt * mtest.T ) {
79
+ // codeName is propagated in an ok:0 error.
80
+
81
+ cmd := bson.D {
82
+ {"insert" , mt .Coll .Name ()},
83
+ {"documents" , []bson.D {}},
84
+ }
85
+ err := mt .DB .RunCommand (mtest .Background , cmd ).Err ()
86
+ assert .NotNil (mt , err , "expected RunCommand error, got nil" )
87
+
88
+ ce , ok := err .(mongo.CommandError )
89
+ assert .True (mt , ok , "expected error of type %T, got %v of type %T" , mongo.CommandError {}, err , err )
90
+ expectedCodeName := "InvalidLength"
91
+ assert .Equal (mt , expectedCodeName , ce .Name , "expected error code name %q, got %q" , expectedCodeName , ce .Name )
92
+ })
93
+
94
+ wcCollOpts := options .Collection ().
95
+ SetWriteConcern (impossibleWc )
96
+ wcMtOpts := mtest .NewOptions ().
97
+ CollectionOptions (wcCollOpts )
98
+ mt .RunOpts ("write concern error" , wcMtOpts , func (mt * mtest.T ) {
99
+ // codeName is propagated for write concern errors.
100
+
101
+ _ , err := mt .Coll .InsertOne (mtest .Background , bson.D {})
102
+ assert .NotNil (mt , err , "expected InsertOne error, got nil" )
103
+
104
+ we , ok := err .(mongo.WriteException )
105
+ assert .True (mt , ok , "expected error of type %T, got %v of type %T" , mongo.WriteException {}, err , err )
106
+ wce := we .WriteConcernError
107
+ assert .NotNil (mt , wce , "expected write concern error, got %v" , we )
108
+
109
+ var expectedCodeName string
110
+ if codeNameVal , err := mt .GetSucceededEvent ().Reply .LookupErr ("writeConcernError" , "codeName" ); err == nil {
111
+ expectedCodeName = codeNameVal .StringValue ()
112
+ }
113
+
114
+ assert .Equal (mt , expectedCodeName , wce .Name , "expected code name %q, got %q" , expectedCodeName , wce .Name )
115
+ })
116
+ }
0 commit comments