erkjson

package
v0.5.11 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2022 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package erkjson allows exporting errors as JSON.

To use this, first embed JSONWrapper in your project's default error kind. Then switch embedding erk.DefaultKind to erk.DefaultPtrKind, to enforce all kinds to be pointers.

Example:

// Declare a default kind for your project:
type DefaultKind struct {
  erk.DefaultPtrKind
  erkjson.JSONWrapper
}

// Declare your kinds:
type ErkNotFound struct { DefaultKind }

// Create your errors:
var ErrSingleItemNotFound = erk.New(&ErkNotFound{}, "a single item with key '{{.key}}' was not found")

// Export your errors to JSON:
jsonError := erkjson.ExportError(err)
// jsonError is an error of type *ErkNotFound, and jsonError.Error() returns the JSON of the original error.

// The original error can be obtained with:
errors.Unwrap(jsonError)

It is not required to embed the JSONWrapper, or use pointers to kinds. However, you will lose the kind as the return type.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExportError

func ExportError(originalError error) error

ExportError to JSON.

If the error's kind implements the JSONWrapable interface, the JSON error is set on the kind. Otherwise, the JSON error is returned as a JSONWrapper.

Types

type JSONWrapable

type JSONWrapable interface {
	error
	SetJSONError(jsonError string)
	SetOriginalError(originalError error)
	IsNil() bool
}

JSONWrapable must be implemented for ExportError to export the error as JSON with the kind's type.

type JSONWrapper

type JSONWrapper struct {
	// contains filtered or unexported fields
}

JSONWrapper can be embedded in error kinds. It is recommended to embed it in your project's default kind.

func (*JSONWrapper) Error

func (w *JSONWrapper) Error() string

Error returns the JSON string.

func (*JSONWrapper) IsNil

func (w *JSONWrapper) IsNil() bool

IsNil returns true if the JSONWrapper is nil.

func (*JSONWrapper) MarshalJSON added in v0.5.4

func (w *JSONWrapper) MarshalJSON() ([]byte, error)

MarshalJSON returns the same thing as Error().

func (*JSONWrapper) SetJSONError

func (w *JSONWrapper) SetJSONError(jsonError string)

SetJSONError string, which is returned by Error().

func (*JSONWrapper) SetOriginalError

func (w *JSONWrapper) SetOriginalError(originalError error)

SetOriginalError returned by Unwrap().

func (*JSONWrapper) Unwrap

func (w *JSONWrapper) Unwrap() error

Unwrap returns the original error.

Jump to

Keyboard shortcuts

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