jsonerror

package module
v0.0.0-...-63ef9a8 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2019 License: MIT Imports: 4 Imported by: 7

README

JSONError for Golang GoDoc

This package is for adding some structure to your error messages. This makes error-handling, debugging and diagnosis for all your Go projects a lot more elegant and simpler. Use it wherever error type is required.

It utilizes the fact that built-in type error is actually an interface.

The package also contains the ErrorCollection struct which allows for accumulation of multiple errors. It is safe to use from multiple concurrent goroutines unlike other comparable packages.

Please Star this package so I can add it to awesome-go.

Refer to documentation on GoDoc because the information below is a small subset of all the features.

Install

go get -u github.com/pjebs/jsonerror

Optional - if you want to output JSON formatted error messages (e.g. for REST API):

go get -u gopkg.in/unrolled/render.v1

Prehistoric Usage - Using Go Standard Library

import (
	"errors"
	"fmt"
)

func main() {
	err := errors.New("emit macho dwarf: elf header corrupted")
	if err != nil {
		fmt.Print(err)
	}
}

//Or alternatively

panic(errors.New("failed"))

Using this package instead

import (
	errors "github.com/pjebs/jsonerror" //aliased for ease of usage
	"math"                              //For realSquareRoot() example function below
)

//EXAMPLE 1 - Creating a JE Struct

err := errors.New(1, "Square root of negative number is prohibited", "Please make number positive or zero") //Domain is optional and not included here

//Or  
err := errors.New(1, "Square root of negative number is prohibited", "Please make number positive or zero", "com.github.pjebs.jsonerror")

//EXAMPLE 2 - Practical Example

//Custom function
func realSquareRoot(n float64) (float64, error) {
	if n < 0 {
		return 0, errors.New(1, "Square root of negative number is prohibited", "Please make number positive or zero")
	} else {
		return math.Sqrt(n), nil
	}
}

//A function that uses realSquareRoot
func main() {

	s, err := realSquareRoot(12.0)
	if err != nil {
		if err.(errors.JE).Code == 1 {
			//Square root of negative number
		} else {
			//Unknown error
		}
		return
	}

	//s is Valid answer
}


Methods

func New(code int, error string, message string, domain ...string) JE

code int - Error code. Arbitrary and set by fiat. Different types of errors should have an unique error code in your project.

error string - A standard description of the error code.

message string - A more detailed description that may be customized for the particular circumstances. May also provide extra information.

domain ...string - Optional It allows you to distinguish between same error codes. Only 1 domain string is allowed.

func (this JE) Render() map[string]string {

Formats JE (JSONError) struct so it can be used by gopkg.in/unrolled/render.v1 package to generate JSON output.

Output JSON formatted error message (i.e. REST API Server response)

import (
	"github.com/codegangsta/negroni" //Using Negroni (https://github.com/codegangsta/negroni)
	errors "github.com/pjebs/jsonerror"
	"gopkg.in/unrolled/render.v1"
	"net/http"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {

		err := errors.New(12, "Unauthorized Access", "Please log in first to access this site")

    	r := render.New(render.Options{})
		r.JSON(w, http.StatusUnauthorized, err.Render())
		return
  	
  	})

  	n := negroni.Classic()
  	n.UseHandler(mux)
  	n.Run(":3000")
}

For the above example, the web server will respond with a HTTP Status Code of 401 (Status Unauthorized), Content-Type as application/json and a JSON response:

{"code":"12","error":"Unauthorized Access","message":"Please log in first to access this site"}

FAQ

What is the domain parameter?

The domain parameter is optional. It allows you to distinguish between same error codes. That way different packages (or different parts of your own project) can use the same error codes (for different purposes) and still be differentiated by the domain identifier.

NB: The domain parameter is not outputted by Render() (for generating JSON formatted output)

How do I use this package?

When you want to return an error (e.g. from a function), just return a JE struct. See the example code above.

Or you can use it with panic().

panic(jsonerror.New(1, "error", "message"))

What are the error codes?

You make them up for your particular project! By fiat, you arbitrarily set each error code to mean a different type of error.

Final Notes

If you found this package useful, please Star it on github. Feel free to fork or provide pull requests. Any bug reports will be warmly received.

PJ Engineering and Business Solutions Pty. Ltd.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultErrorFormatter = func(i int, err error, str *string) {
	*str = fmt.Sprintf("%s\n%d:%s", *str, i, err.Error())
}

DefaultErrorFormatter represents the default formatter for displaying the collection of errors.

Functions

func IsNil

func IsNil(err error) bool

IsNil returns whether an error is nil or not. It can be used with ErrorCollection or generic errors

Types

type DuplicatationOptions

type DuplicatationOptions int

ErrorCollection can be configured to allow duplicates.

const (
	AllowDuplicates                 DuplicatationOptions = 0
	RejectDuplicatesIgnoreTimestamp DuplicatationOptions = 1 //Ignore timestamp information in JE struct
	RejectDuplicates                DuplicatationOptions = 2
)

type ErrorCollection

type ErrorCollection struct {
	DuplicatationOptions DuplicatationOptions
	Errors               []error
	Formatter            func(i int, err error, str *string)
	// contains filtered or unexported fields
}

ErrorCollection allows multiple errors to be accumulated and then returned as a single error. ErrorCollection can be safely used by concurrent goroutines.

func NewErrorCollection

func NewErrorCollection(dup ...DuplicatationOptions) *ErrorCollection

Creates a new empty ErrorCollection. When `dup` is set, any duplicate error message is discarded and not appended to the collection

func (*ErrorCollection) AddError

func (ec *ErrorCollection) AddError(err error)

AddError appends an error to the error collection. It is safe to use from multiple concurrent goroutines.

func (*ErrorCollection) AddErrorCollection

func (ec *ErrorCollection) AddErrorCollection(errs *ErrorCollection)

AddErrorCollection appends an entire ErrorCollection to the receiver error collection. It is safe to use from multiple concurrent goroutines.

func (*ErrorCollection) AddErrors

func (ec *ErrorCollection) AddErrors(errs ...error)

AddErrors appends multiple errors to the error collection. It is safe to use from multiple concurrent goroutines.

func (*ErrorCollection) Error

func (ec *ErrorCollection) Error() string

Error return a list of all contained errors. The output can be formatted by setting a custom Formatter.

type JE

type JE struct {
	Code   int
	Domain string

	DisplayTime bool
	// contains filtered or unexported fields
}

JE allows errors to contain Code, Domain, Error and Message information. Only Code and Domain are exported so that once a JE struct is created, the key elements are static.

func New

func New(code int, error string, message string, domain ...string) JE

New creates a new JE struct. Domain is optional but can be at most 1 string.

func NewAndDisplayTime

func NewAndDisplayTime(code int, error string, message string, domain ...string) JE

NewAndDisplayTime creates a new JE struct and configures it to display the timestamp. Domain is optional but can be at most 1 string.

func (JE) Error

func (j JE) Error() string

Error generates a string that neatly formats the contents of the JE struct. JSONError satisfies the error interface. Useful with panic().

func (JE) Render

func (j JE) Render() map[string]string

For use with package: "gopkg.in/unrolled/render.v1". Can easily output properly formatted JSON error messages for REST API services.

func (JE) Time

func (j JE) Time() time.Time

Return the time the JE struct was created

Jump to

Keyboard shortcuts

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