Example #1
0
func Example(t *testing.T) {
	InvalidRequest := errors.NewClass("Invalid request",
		SetStatusCode(http.StatusBadRequest))

	process := func() error {
		// this method is some sample method somewhere that's doing request
		// processing
		return InvalidRequest.New("missing field or something")
	}

	handler := func(err error) {
		// this method is some sample method somewhere that's figuring out how
		// to display various errors to a user.
		if err != nil {
			code := GetStatusCode(err, 500)
			message := GetErrorBody(err)
			log.Printf("HTTP error %d: %s\n%s", code, message, err)
			writeError(message, code)
		}
	}

	// http event loop
	handler(process())
}
Example #2
0
	EXIT_JOB          = ExitCode(10) // used to indicate a job reported a nonzero exit code (from cli commands that execute a single job).
)

var ExitCodeKey = errors.GenSym()

/*
	CLI errors are the last line: they should be formatted to be user-facing.
	The main method will convert a CLIError into a short and well-formatted
	message, and will *not* include stack traces unless the user is running
	with debug mode enabled.

	CLI errors are an appropriate wrapping for anything where we can map a
	problem onto something the user can understand and fix.  Errors that are
	a repeatr bug or unknown territory should *not* be mapped into a CLIError.
*/
var Error *errors.ErrorClass = errors.NewClass("CLIError")

/*
	Use this to set a specific error code the process should exit with
	when producing a `cli.Error`.

	Example: `cli.Error.NewWith("something terrible!", SetExitCode(EXIT_BADARGS))`
*/
func SetExitCode(code ExitCode) errors.ErrorOption {
	return errors.SetData(ExitCodeKey, code)
}

/*
	Exit errors may be raised to immediately transition to we're done (and
	specify an `ExitCode`), but generate slightly less of a sadface than
	`cli.Error`: use them for graceful exits.
Example #3
0
// Copyright (C) 2016 JT Olds
// See LICENSE for copying information

package webhelp

import (
	"net/http"

	"github.com/spacemonkeygo/errors"
	"github.com/spacemonkeygo/errors/errhttp"
)

var (
	HTTPError     = errors.NewClass("HTTP Error", errors.NoCaptureStack())
	ErrBadRequest = HTTPError.NewClass("Bad request",
		errhttp.SetStatusCode(http.StatusBadRequest))
	ErrNotFound = ErrBadRequest.NewClass("Not found",
		errhttp.SetStatusCode(http.StatusNotFound))
	ErrMethodNotAllowed = ErrBadRequest.NewClass("Method not allowed",
		errhttp.SetStatusCode(http.StatusMethodNotAllowed))
	ErrInternalServerError = HTTPError.NewClass("Internal server error",
		errhttp.SetStatusCode(http.StatusInternalServerError))
	ErrUnauthorized = HTTPError.NewClass("Unauthorized",
		errhttp.SetStatusCode(http.StatusUnauthorized))
)

func Redirect(w ResponseWriter, r *http.Request, redirectTo string) error {
	http.Redirect(w, r, redirectTo, http.StatusSeeOther)
	return nil
}
Example #4
0
package scheduler

import (
	"github.com/spacemonkeygo/errors"
)

// grouping, do not instantiate
var Error *errors.ErrorClass = errors.NewClass("SchedulerError")

// error when a scheduler's queue was full and could not enqueue a forumla.
var QueueFullError *errors.ErrorClass = Error.NewClass("QueueFullError")
Example #5
0
	"bytes"
	"encoding/json"
	"fmt"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/spacemonkeygo/errors"
)

type Type string

var (
	GridError = errors.NewClass("grid error")
)

const (
	Empty   Type = "empty"
	Wall    Type = "wall"
	Player  Type = "player"
	Battery Type = "battery"
	Laser   Type = "laser"
)

func (t Type) MarshalJSON() ([]byte, error) {
	return json.Marshal(string(t))
}

func (t *Type) UnmarshalJSON(p []byte) (err error) {
Example #6
0
}

/*
	RecordIterator is used for walking Bucket contents in hash-ready order.
	It's specified separately from Record for three reasons: There will be many
	Record objects, and so they should be small (the iterators tend to require
	at least another two words of memory); and the Record objects are
	serializable the same way for all implementations of Bucket (the iterators
	may work differently depending on how data is heaped in the Bucket impl).
*/
type RecordIterator interface {
	treewalk.Node
	Record() Record
}

var InvalidFilesystem *errors.ErrorClass = errors.NewClass("InvalidFilesystem")

/*
	PathCollision is reported when the same file path is submitted to a `Bucket`
	more than once.  (Some formats, for example tarballs, allow the same filename
	to be recorded twice.  We consider this poor behavior since most actual
	filesystems of course will not tolerate this, and also because it begs the
	question of which should be sorted first when creating a deterministic
	hash of the whole tree.)
*/
var PathCollision *errors.ErrorClass = InvalidFilesystem.NewClass("PathCollision")

/*
	MissingTree is reported when iteration over a filled bucket encounters
	a file that has no parent nodes.  I.e., if there's a file path "./a/b",
	and there's no entries for "./a", it's a MissingTree error.
Example #7
0
// Copyright (C) 2015 Space Monkey, Inc.

package client

import (
	"encoding/json"
	"io"
	"io/ioutil"

	"github.com/spacemonkeygo/errors"

	"sm/final/game"
)

var (
	ClientError = errors.NewClass("client error")
	ServerError = errors.NewClass("server error")
)

func errBody(r io.Reader) string {
	var msg [256]byte
	n, _ := r.Read(msg[:])
	return string(msg[:n])
}

func readAndParseState(r io.Reader) (state game.TurnState, err error) {
	json_bytes, err := ioutil.ReadAll(r)
	if err != nil {
		return state, ServerError.Wrap(err)
	}
	err = json.Unmarshal(json_bytes, &state)
Example #8
0
package placer

import (
	"github.com/spacemonkeygo/errors"
)

var Error *errors.ErrorClass = errors.NewClass("PlacerError")
Example #9
0
	"github.com/dustin/go-humanize"
	"github.com/golang/glog"
	"github.com/spacemonkeygo/errors"

	"github.com/uwedeportivo/romba/config"
)

type countVisitor struct {
	numBytes       int64
	numFiles       int
	commonRootPath string
	master         Master
}

var (
	Error          = errors.NewClass("Worker Error")
	StopProcessing = Error.NewClass("Stop Processing Error")
)

func CommonRoot(pa, pb string) string {
	if pa == "" || pb == "" {
		return ""
	}

	pac := filepath.Clean(pa)
	pbc := filepath.Clean(pb)

	va := filepath.VolumeName(pac)
	vb := filepath.VolumeName(pbc)

	if va != vb {
Example #10
0
package def

import (
	"github.com/spacemonkeygo/errors"
)

/*
	Validation error is a base class for anything that matches the description
	of an HTTP 400.  (Unless the validation should have been performed at an
	earlier stage, and the current check is only for sanity; then, if it fails
	and it's considered a compile-time boo boo, use `errors.ProgrammerError`.)
*/
var ValidationError *errors.ErrorClass = errors.NewClass("ValidationError")

/*
	UnsupportedPlatform is an error raised when an operation is unavailable on the
	OS.  (Say, setting utime on a symlink on a mac.)
*/
var UnsupportedPlatform *errors.ErrorClass = errors.NewClass("UnsupportedPlatform")

var ConfigError *errors.ErrorClass = errors.NewClass("ConfigError")

func newConfigValTypeError(expectedKey, mustBeA string, wasActually string) *errors.Error {
	return ConfigError.New("config key %q must be a %s; was %s", expectedKey, mustBeA, wasActually).(*errors.Error)
}
Example #11
0
package vm

import (
	"github.com/spacemonkeygo/errors"
	"io"
)

var ErrPoolLimitReached = errors.NewClass("No more resource can be acquired")

// 资源对象
type Res interface {
	Id() int
	Get() interface{}
	Set(interface{})
}
type ResValCreator func(ResPool) interface{}

// 资源池
type ResPool interface {
	Acquire() (Res, error)
	Release(Res)
	Get(int) Res
	SetCreator(ResValCreator)
	Creator() ResValCreator
}
type res struct {
	id  int
	val interface{}
}

func (r *res) Get() interface{} {
Example #12
0
package asm

import (
	"fmt"
	"github.com/spacemonkeygo/errors"
)

var ErrDataToShort = errors.NewClass("ErrDataToShort")
var ErrWrongInst = errors.NewClass("ErrWrongInst")

type Operand struct {
	// Address or Immediate value
	Val         int32
	AddressMode AddressMode
	// Symbol associated to this operand
	Symbol string
}

//func (o *Operand)Get() int {
//	switch (o.AddrMode) {
//	case AM_REGISTER:
//		return o.Register.Get();
//	case AM_REGISTER_DEFERRED:
//		return o.VM.GetInt(o.VM.Register(RegisterType(o.Val)).Get());
//	case AM_IMMEDIATE:
//		return int(int32(o.Val));// must convert to int32 first
//	case AM_DIRECT:
//		return o.VM.GetInt(int(o.Val));
//	}
//	panic("Unexcepted")
//}
Example #13
0
	std_errors "errors"
	"fmt"
	math_rand "math/rand"
	"strings"
	"sync"
	"time"

	"github.com/spacemonkeygo/errors"
	"github.com/spacemonkeygo/spacelog"

	"sm/final/grid"
	"sm/final/renderer"
)

var (
	GameError = errors.NewClass("game error", errors.NoCaptureStack())
	JoinError = GameError.NewClass("join error")

	logger = spacelog.GetLogger()
)

type Command string

const (
	selfDestruct Command = "kaboom"
	Join         Command = "join"
	Noop         Command = "noop"
	MoveForward  Command = "move"
	RotateLeft   Command = "left"
	RotateRight  Command = "right"
	FireLaser    Command = "fire"
Example #14
0
package fs

import (
	"github.com/spacemonkeygo/errors"
)

var Error *errors.ErrorClass = errors.NewClass("FSError") // grouping, do not instantiate

/*
	`BreakoutError` is raised when processing a filesystem description where links
	(symlinks, hardlinks) are constructed in such a way that they would reach
	out of the base directory.  Encountering these in a well-formed filesystem
	description is basically an attempted attack.
*/
var BreakoutError *errors.ErrorClass = Error.NewClass("FSBreakoutError")

func ioError(err error) {
	panic(Error.Wrap(errors.IOError.Wrap(err)))
}
Example #15
0
// ## Deps
//     go get github.com/SpaceMonkeyGo/errors
//

package lib

import (
	Logger "github.com/JasonGiedymin/test-flight/lib/logging"
	"github.com/SpaceMonkeyGo/errors"
)

// == Default vars ==
var (
	defaultDir    = "./"
	BadDir        = errors.NewClass("Can't read the current directory")
	FileCheckFail = errors.NewClass("File Check Failed")
	mainYaml      = RequiredFile{Name: "main yaml", FileName: "main.yml", FileType: "f"}
	buildFile     = RequiredFile{Name: Constants().buildFileName, FileName: Constants().buildFileName, FileType: "f"}
	AnsibleFiles  = []RequiredFile{mainYaml}
)

// Creates a list of required files needed by TestFlight using
// templateDir via config file as a basis.
func TestFlightFiles(templateDir string) []RequiredFile {
	return []RequiredFile{
		{Name: "Test-Flight dir", FileName: templateDir, FileType: "d"}, //, These will actually be generated
		// RequiredFiles: []RequiredFile{
		//   {Name: "Ansible inventory file used for Test-Flight", FileName: "inventory", FileType: "f"},
		//   {Name: "Ansible playbook file used for Test-Flight", FileName: "playbook.yml", FileType: "f"},
		// },
Example #16
0
		    - DataDNE (not necessarily a panic-worthy offense)
		    - HashMismatchError (this is somewhere between extremely rudely failing component and outright malice)
		  - MoorError (from either materialize or scan: ran out of space, didn't have perms, something)

	All of these are errors that can be raised from using transmats.
	(They're not all grouped under TransmatError because they're not all
	the transmat's fault, per se; fixing them requires looking afield.)

	Additionally, these other systems may fail, but are rare, internal, and serious:
		- Error
		  - PlacerError
		  // actually that's it... assemblers, to date, don't represent enough
		  //  code to have their own interesting failure modes.

*/
var Error *errors.ErrorClass = errors.NewClass("IntegrityError") // grouping, do not instantiate // n.b. the ambiguity and alarmingness of this error name is the clearest example of why this package needs rethinking on the name.

/*
	Raised to indicate that some configuration is missing or malformed.
*/
var ConfigError *errors.ErrorClass = Error.NewClass("ConfigError")

/*
	Raised to indicate a serious internal error with a transmat's functioning.

	Typically these indicate a need for the whole program to stop; examples are
	the repeatr daemon hitting permissions problems in the main work area,
	or running out of disk space, or something equally severe.

	Errors relating to the either the warehouse, the data integrity checks,
	or the operational theater on the local filesystem are all different
Example #17
0
	_ "github.com/lib/pq"
	_ "github.com/mattn/go-sqlite3"
	"github.com/spacemonkeygo/errors"
	"github.com/spacemonkeygo/errors/errhttp"
)

var (
	dbType = flag.String("db", "postgres", "the database type to use. "+
		"can be postgres or sqlite3")
	dbConn = flag.String("db.conn",
		"user=cwbench database=cwbench password=password",
		"the database connection string")
	searchParallelism = flag.Int("parallelism", runtime.NumCPU()+1,
		"number of parellel search queries to execute")

	Err         = errors.NewClass("error")
	ErrNotFound = Err.NewClass("not found", errhttp.SetStatusCode(404))
	ErrDenied   = Err.NewClass("denied", errhttp.SetStatusCode(405))
	ErrBadDims  = Err.NewClass("wrong dimensions", errhttp.SetStatusCode(400))
)

type Data struct {
	db gorm.DB
}

func NewData() (*Data, error) {
	db, err := gorm.Open(*dbType, *dbConn)
	if err != nil {
		return nil, Err.Wrap(err)
	}
	return &Data{db: db}, nil
Example #18
0
package executor

import (
	"github.com/spacemonkeygo/errors"
)

// grouping, do not instantiate
var Error *errors.ErrorClass = errors.NewClass("ExecutorError")

/*
	Error raised when an executor cannot operate due to invalid setup.
*/
var ConfigError *errors.ErrorClass = Error.NewClass("ExecutorConfigError")

/*
	Error raised when there are serious issues with task launch.

	Occurance of TaskExecError may be due to OS-imposed resource limits
	or other unexpected problems.  They should not be seen in normal,
	healthy operation.
*/
var TaskExecError *errors.ErrorClass = Error.NewClass("ExecutorTaskExecError")

/*
	Error raised when a command is not found inside the execution environment.

	Often just indicative of user misconfiguration (and thus this is not a
	child of TaskExecError, which expresses serious system failures).
*/
var NoSuchCommandError *errors.ErrorClass = Error.NewClass("NoSuchCommandError")
Example #19
0
	"github.com/golang/glog"
	"github.com/uwedeportivo/romba/types"
)

const (
	xmlPrefix        = "<?xml"
	xmlPrefixWithBOM = "\xef\xbb\xbf<?xml"
)

type parser struct {
	ll *lexer
	d  *types.Dat
}

var (
	ParseError    = errors.NewClass("DAT Parse Error")
	XMLParseError = errors.NewClass("XML DAT Parse Error")

	lineNumberErrorKey = errors.GenSym()
	filePathErrorKey   = errors.GenSym()
)

func ErrorLineNumber(err error) int {
	v, ok := errors.GetData(err, lineNumberErrorKey).(int)
	if !ok {
		return -1
	}
	return v
}

func ErrorFilePath(err error) string {
Example #20
0
package pwsafe

import (
	"time"

	"github.com/spacemonkeygo/errors"
)

var (
	// Error is a generic error class for pwsafe.
	Error = errors.NewClass("pwsafe")

	// IOError represents an io error.
	IOError = Error.NewClass("io error")

	// BadPassphrase indicates that the passphrase was bad.
	BadPassphrase = Error.NewClass("bad passphrase", errors.NoCaptureStack())

	// BadTag indicates that the tag on the database file is unexpected.
	BadTag = Error.NewClass("bad tag", errors.NoCaptureStack())

	// Corrupted indicates that the database has been corrupted.
	Corrupted = Error.NewClass("corrupted", errors.NoCaptureStack())
)

// Database represents a pwsafe database.
type Database interface {

	// Version returns a version string for the database.
	Version() string