errors

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2024 License: AGPL-3.0 Imports: 3 Imported by: 1

README

Responsable Errors

This is a small go library that provides errors that can be more useful in the context of a web app.

Overview

Use this library to wrap errors so that an error handler in your web app can use them in a response.

I plan to create a middleware library for Gin soon to utilize this library.

Installation

Use go modules.

import errors "codeberg.org/danjones000/responsable-errors"

Usage

err := SomethingThatReturnsAnError()
err = errors.Errorf(418, "I am a teapot. %w", err)

// Later on, when you're returning something
// This example uses gin.
c.JSON(err.GetStatus(), gin.H{"error":err.GetMsg()})

Or:

user, err := db.GetUser(id)
if err != nil {
    return errors.NotFound("%w", err).Msg("User %d not found", id)
}

In the second example, err.GetStatus() returns 404, err.GetMsg() returns "User XX not found", and err.Error() returns the error message from the original error. Also, err.Unwrap() will return the original error, but you'll have to type cast to UnwrappableError first.

Future plans

Any suggestions/requests?

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ResponsableError

type ResponsableError interface {
	json.Marshaler
	Error() string
	Status() int
	Msg() string
	JSON() any
}

ResponsableError is an error that has information useful in an HTTP response. The string returned by Error should be suitable for logging useful information to assist debugging the error.

Status should return an appropriate HTTP status. It must not return < 100 || >= 600.

Msg should return a message suitable to display to the end user. If the message returned by Error is safe for the end user, it may simply call that.

JSON should return something that can be marshalled to JSON for the response body. It can be something as simple as map[string]string{"error":err.Msg()}. JSON's return value should be used by MarshalJSON()

type SettableError

type SettableError interface {
	ResponsableError
	SetStatus(int) SettableError
	SetMsg(string, ...any) SettableError
	SetField(string, any) SettableError
}

SettableError is a ResponsableError which can be modified after initial creation.

The SetStatus method can set the status, while the SetMsg method can set user message. If any values are passed after the message, it should be passed to fmt.Sprintf for formatting.

Methods are chainable.

SetStatus should not use a value outside of 100-599. It may either ignore such values, or panic.

SetField should add some metadata to the error, which will be included in the data returned by JSON()

func Errorf

func Errorf(status int, format string, parts ...any) SettableError

Returns a SettableError formatted from the message, with the specified status. Errorf passes the heavy lifting off to fmt.Errorf, and returns a similar error. If one error is passed in the format, this will return an UnwrappableError. If more than one error is passed in the format, this will return an UnwrappableErrors.

The Msg method may also be formatted.

If you want a different user message, use Msg, such as:

err := errors.Errorf(http.StatusNotFound, "%w", sqlError).SetMsg("user not found %d", userId)

func NewBadRequest

func NewBadRequest(format string, parts ...any) SettableError

Represents a 400 error.

func NewForbidden added in v0.2.1

func NewForbidden() SettableError

A 403 error with the error message "Forbidden"

func NewInternalError

func NewInternalError(format string, parts ...any) SettableError

Represents a 500 error. For this error, the user error is preset to "Unknown Error".

func NewNotFound

func NewNotFound(format string, parts ...any) SettableError

Represents a 404 error.

func NewUnauthorized added in v0.2.1

func NewUnauthorized() SettableError

A 401 error with the error message "Unauthorized"

type UnwrappableError

type UnwrappableError interface {
	ResponsableError
	Unwrap() error
}

UnwrappableError allows a ResponsableError to wrap another error. It may be appropriate for Error() to delegate to the wrapped error.

type UnwrappableErrors

type UnwrappableErrors interface {
	ResponsableError
	Unwrap() []error
}

UnwrappableErrorrs allows a ResponsableError to wrap multiple errors. It may be appropriate for Error() to either delegate to the first error, the last error, or to concatenate the return values of all wrapped errors, similar to errors returned by errors.Join

Jump to

Keyboard shortcuts

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