error.go 1.52 KB
Newer Older
Steven Allen's avatar
Steven Allen committed
1
package cmds
2

3 4 5
import (
	"encoding/json"
	"errors"
keks's avatar
keks committed
6
	"fmt"
7 8
)

9 10 11 12 13
// ErrorType signfies a category of errors
type ErrorType uint

// ErrorTypes convey what category of error ocurred
const (
Steven Allen's avatar
Steven Allen committed
14 15 16 17 18 19 20 21 22 23 24
	// ErrNormal is a normal error. The command failed for some reason that's not a bug.
	ErrNormal ErrorType = iota
	// ErrClient means the client made an invalid request.
	ErrClient
	// ErrImplementation means there's a bug in the implementation.
	ErrImplementation
	// ErrRateLimited is returned when the operation has been rate-limited.
	ErrRateLimited
	// ErrForbidden is returned when the client doesn't have permission to
	// perform the requested operation.
	ErrForbidden
25 26 27 28 29 30 31 32
)

// Error is a struct for marshalling errors
type Error struct {
	Message string
	Code    ErrorType
}

keks's avatar
keks committed
33 34 35
// Errorf returns an Error with the given code and format specification
func Errorf(code ErrorType, format string, args ...interface{}) Error {
	return Error{
ia's avatar
ia committed
36
		Code:    code,
keks's avatar
keks committed
37 38 39 40
		Message: fmt.Sprintf(format, args...),
	}
}

41 42 43
func (e Error) Error() string {
	return e.Message
}
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

func (e Error) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Message string
		Code    ErrorType
		Type    string
	}{
		Message: e.Message,
		Code:    e.Code,
		Type:    "error",
	})
}

func (e *Error) UnmarshalJSON(data []byte) error {
	var w struct {
		Message string
		Code    ErrorType
		Type    string
	}

	err := json.Unmarshal(data, &w)
	if err != nil {
		return err
	}

	if w.Type != "error" {
		return errors.New("not of type error")
	}

	e.Message = w.Message
	e.Code = w.Code

	return nil
}