errors

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2025 License: GPL-3.0 Imports: 4 Imported by: 0

README

go-errors

A simple error handling library for Go, designed for clean JSON serialization, safe error wrapping, and HTTP-friendly error responses.

✨ Features

  • Unified Error interface — all errors can be serialized to valid JSON.
  • Generic errors with names, messages, and original error support.
  • HTTP errors with built-in status codes and structured responses.
  • Circular reference protection when marshalling to JSON.
  • Automatic wrapping of non-JSON-compatible errors.
  • Simple, idiomatic API with no external dependencies (except for circular reference checking).

📦 Installation

go get github.com/iolave/go-errors

🚀 Quick Start

Creating a generic error
import errors "github.com/iolave/go-errors"

func main() {
    err := errors.New("configuration file missing").(errors.Error)
    fmt.Println(err.JSON())
    // {"name":"error","message":"configuration file missing"}
}
Wrapping an existing error
import (
    "fmt"
    errors "github.com/iolave/go-errors"
)

func main() {
    err := fmt.Errorf("configuration file missing")
    fmt.Println(errors.Wrap(err).(errors.Error).JSON())
    // {"name":"error","message":"configuration file missing","original": {}}
}
Named errors
import errors "github.com/iolave/go-errors"

func main() {
    err := errors.NewWithName("my_error", "configuration file missing").(errors.Error)
    fmt.Println(err.JSON())
    // {"name":"my_error","message":"configuration file missing"}
}
HTTP errors
import errors "github.com/iolave/go-errors"

func main() {
    err := errors.NewNotFoundError("user not found", nil).(errors.Error)
    fmt.Println(err.JSON())
    // {"statusCode":404,"name":"not_found_error","message":"user not found","error":null}
}

Available constructors:

  • NewBadRequestError(message string, err error) error
  • NewNotFoundError(message string, err error) error
  • NewInternalServerError(message string, err error) error
  • NewUnauthorizedError(message string, err error) error
  • NewForbiddenError(message string, err error) error
  • NewConflictError(message string, err error) error
  • NewTooManyRequestsError(message string, err error) error
  • NewBadGatewayError(message string, err error) error
  • NewServiceUnavailableError(message string, err error) error
  • NewGatewayTimeoutError(message string, err error) error

Each has a corresponding func(message string, err error) error signature.


📜 API Overview

Error interface

All errors implement:

type Error interface {
    error
    JSON() []byte
}
Conversion
  • ToError(err error) Error — asserts that an error implements Error (panics otherwise).
Generic Errors
  • New(msg string) error
  • NewWithName(name, msg string) error
  • NewWithNameAndErr(name, msg string, orig error) error
  • Wrap(err error) error
HTTP Errors
  • NewHTTPError(statusCode int, name, message string, err error) error

Convenience constructors listed above.


🛡️ JSON Safety

errors automatically:

  • Detects circular references and replaces them with explanatory placeholder errors.
  • Wraps non-Error types so their content is still available in serialized form.
  • Ensures JSON() always returns valid JSON.
🤝 Contributing

Pull requests are welcome!

If you add features or change APIs, please include tests and update the README accordingly.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New added in v1.0.0

func New(msg string) error

New creates a new GenericError with it's name set to "error", the message set to the given message.

func NewBadGatewayError

func NewBadGatewayError(message string, err error) error

NewBadGatewayError creates a new HTTPError with a 502 status code.

func NewBadRequestError

func NewBadRequestError(message string, err error) error

NewBadRequestError creates a new HTTPError with a 400 status code.

func NewConflictError added in v1.0.0

func NewConflictError(message string, err error) error

NewConflictError creates a new HTTPError with a 409 status code.

func NewForbiddenError

func NewForbiddenError(message string, err error) error

NewForbiddenError creates a new HTTPError with a 403 status code.

func NewGatewayTimeoutError

func NewGatewayTimeoutError(message string, err error) error

NewGatewayTimeoutError creates a new HTTPError with a 504 status code.

func NewHTTPError added in v1.0.0

func NewHTTPError(statusCode int, name, message string, err error) error

NewHTTPError creates a new HTTPError.

func NewInternalServerError

func NewInternalServerError(message string, err error) error

NewInternalServerError creates a new HTTPError with a 500 status code.

func NewNotFoundError

func NewNotFoundError(message string, err error) error

NewNotFoundError creates a new HTTPError with a 404 status code.

func NewServiceUnavailableError added in v1.0.0

func NewServiceUnavailableError(message string, err error) error

NewServiceUnavailableError creates a new HTTPError with a 503 status code.

func NewTooManyRequestsError added in v1.0.0

func NewTooManyRequestsError(message string, err error) error

NewTooManyRequestsError creates a new HTTPError with a 429 status code.

func NewUnauthorizedError

func NewUnauthorizedError(message string, err error) error

NewUnauthorizedError creates a new HTTPError with a 401 status code.

func NewWithName added in v1.0.0

func NewWithName(name, msg string) error

NewWithName creates a new GenericError with it's name set to the given name and the message set to the given message.

func NewWithNameAndErr added in v1.0.0

func NewWithNameAndErr(name, msg string, orig error) error

NewWithNameAndErr creates a new GenericError with it's name set to the given name, the message set to the given message and the original property set to the given original error.

func Wrap added in v1.0.0

func Wrap(err error) error

Wrap wraps an error into a GenericError. It sets the name of the error to "error", the message to the original error.Error() value and the original property to the original error.

Types

type Error

type Error interface {
	// ensures that the error implements the error interface
	error

	// JSON returns the JSON representation of the error
	// and it must ensure that the returned value is
	// is a valid JSON even if the error is not marshallable
	// by handling the error returned by json.Marshal
	JSON() []byte
}

Error is an interface for errors that can be marshalled to JSON

func ToError added in v1.0.0

func ToError(err error) Error

ToError asserts that the error is an Error and returns it. Otherwise, it panics.

This function is useful when you want to ensure that the error is an Error or you know beforehand that the error is an Error and you want to use Error methods.

type GenericError added in v1.0.0

type GenericError struct {
	// Name is the name of the error
	Name string `json:"name"`

	// Message is the message of the error
	Message string `json:"message"`

	// Original is an optional original error
	Original error `json:"original,omitempty"`
}

func (GenericError) Error added in v1.0.0

func (e GenericError) Error() string

Error returns a string concatenation of the name, message and original error.

func (GenericError) JSON added in v1.0.0

func (e GenericError) JSON() []byte

JSON returns the JSON representation of the error

If the Orginal property is not marshallable, it will be replaced with a marshallable error indicating why the original error is not marshallable and it's original error returned by the Error() method.

type HTTPError added in v1.0.0

type HTTPError struct {
	StatusCode int    `json:"statusCode"`
	Name       string `json:"name"`
	Message    string `json:"message"`
	Err        error  `json:"error"`
}

HTTPError is a struct that represents an HTTP error and it implements the Error interface.

func (*HTTPError) Error added in v1.0.0

func (e *HTTPError) Error() string

Error returns a string concatenation of the name and message. If th Err property is not nil, it will be returned in the message.

func (HTTPError) JSON added in v1.0.0

func (e HTTPError) JSON() []byte

JSON returns the bytes of the JSON representation of the error.

If the Err property is not marshalable, it will be replaced with a marshalable error indicating why it is not marshalable.

If the Err property is not an implementation of the Error interface, it will be replaced with a wrapped version of it to ensure that the error is marshallable and content will be shown.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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