Permalink
Browse files

Add ErrorCode.Class()

This returns the "class" of an error, which supports Name() to get the
"condition name".
  • Loading branch information...
1 parent 8f04589 commit 5690e1085bef5ade23fc604ed38419d9a4c4f3d2 @johto johto committed Jan 18, 2014
Showing with 37 additions and 0 deletions.
  1. +20 −0 conn_test.go
  2. +17 −0 error.go
View
@@ -894,6 +894,26 @@ func TestCommit(t *testing.T) {
}
}
+func TestErrorClass(t *testing.T) {
+ db := openTestConn(t)
+ defer db.Close()
+
+ _, err := db.Query("SELECT int 'notint'")
+ if err == nil {
+ t.Fatal("expected error")
+ }
+ pge, ok := err.(*Error)
+ if !ok {
+ t.Fatalf("expected *pq.Error, got %#+v", err)
+ }
+ if pge.Code.Class() != "22" {
+ t.Fatalf("expected class 28, got %v", pge.Code.Class())
+ }
+ if pge.Code.Class().Name() != "data_exception" {
+ t.Fatalf("expected data_exception, got %v", pge.Code.Class().Name())
+ }
+}
+
func TestParseOpts(t *testing.T) {
tests := []struct {
in string
View
@@ -52,6 +52,23 @@ func (ec ErrorCode) Name() string {
return errorCodeNames[ec]
}
+// ErrorClass is only the class part of an error code
+type ErrorClass string
+
+// Name returns the condition name of an error class. It is equivalent to the
+// condition name of the "standard" error code (i.e. the one having the last
+// three characters "000").
+func (ec ErrorClass) Name() string {
+ return errorCodeNames[ErrorCode(ec + "000")]
+}
+
+// Class returns the error class, e.g. "28"
+//
+// See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for details
+func (ec ErrorCode) Class() ErrorClass {
+ return ErrorClass(ec[0:2])
+}
+
// errorCodeNames is a mapping between five digit Error Codes and the human
// readable "Condition Name" for that error. It is derived from the list at
// http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html

0 comments on commit 5690e10

Please sign in to comment.