pqerrors

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 9, 2018 License: Apache-2.0 Imports: 0 Imported by: 0

README

pqerrors

Build Status GoDoc Supported Go Versions Go Report Card GitHub Release

pqerrors is a Go library that provides constants to make handling pq errors easier

Example Usage:

Error Classes
    var err error // err from database/sql
    if e, ok := err.(pq.Error); ok {
        switch e.Code.Class() {
        case pqerrcls.NoData:
             // Handle error
        case pqerrcls.IntegrityConstraintViolation:
             // Handle error
        default:
            // Handle unexpected error
        }
    }
Error Codes
    var err error // err from database/sql
    if e, ok := err.(pq.Error); ok {
        switch e.Code {
        case pqerrcode.DataExceptionNullValueNotAllowed:
             // Handle error
        case pqerrcode.IntegrityConstraintViolationUniqueViolation:
             // Handle error
        default:
            // Handle unexpected error
        }
    }

How to update error class and code constants:

  1. Copy the table of Postgres errors into errors_table.txt
  2. Run go generate
  3. Ensure that tests still pass: go test -v
  4. Commit the changes
  5. Open a PR

Documentation

Overview

Package pqerrors provides constants for pq's (github.com/lib/pq) ErrorClass and ErrorCode

ErrorClass constants are in the pqerrcls package and ErrorCode constants are in the pqerrcode package

Example
package main

import (
	"fmt"

	"github.com/dhui/pqerrors/pqerrcls"
	"github.com/dhui/pqerrors/pqerrcode"
	"github.com/lib/pq"
)

func main() {
	pqErr := pq.Error{Code: pq.ErrorCode("23505")}
	var err error = pqErr // err from database/sql
	if e, ok := err.(pq.Error); ok {
		// Example usage of pqerrcls
		switch e.Code.Class() {
		case pqerrcls.IntegrityConstraintViolation:
			fmt.Println("Class success!")
		default:
			fmt.Println("Unexpected error class:", e.Code.Class(), e.Code.Class().Name())
		}

		// Example usage of pqerrcode
		switch e.Code {
		case pqerrcode.IntegrityConstraintViolationUniqueViolation:
			fmt.Println("Code success!")
		default:
			fmt.Println("Unexpected error code:", e.Code, e.Code.Name())
		}
	}
}
Output:

Class success!
Code success!

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL