tiny_errors

package
v1.1.16 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2024 License: MIT Imports: 5 Imported by: 2

README

Tiny Errors

This package is needed to make your errors standardized.

The main idea is to have an array of errors with a specific codes and messages.

Examples

Initialization

You can init your errors globally for a project.

main.go:

package main

import (
  "github.com/Moranilt/http-utils/tiny_errors"
)

const (
  ERR_NotValidToken = 1000
  ERR_TokenExpired = 1001

  ERR_UserNotFound = 2000
  ERR_UserAlreadyExists = 2001
)

var globalErrors = map[int]string{
  ERR_NotValidToken: "Not valid token",
  ERR_TokenExpired: "Token expired",
  ERR_UserNotFound: "User not found",
  ERR_UserAlreadyExists: "User already exists",
}

func main() {
  // ...
  tiny_errors.Init(globalErrors)

}

repository.go:

func (repo *Repository) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, tiny_errors.ErrorHandler) {
  // ...

  if err != nil {
    return nil, tiny_errors.New(
      ERR_UserNotFound,
      tiny_errors.SetDetail("user_id", req.ID),
    )
  }

  // ...
}
// Output: {"error": {"code": 2000, "message": "User not found", "details": {"user_id": "1"}}}

You can use details to provide more information into response to help you to debug or make human readable messages with extra data from details field.

Without initialization

You can use it without initialization as simple as you think:

func (repo *Repository) GetUser(ctx context.Context, req *GetUserRequest) (*GetUserResponse, tiny_errors.ErrorHandler) {
  // ...

  if err != nil {
    return nil, tiny_errors.New(
      ERR_UserNotFound,
      tiny_errors.Message("User not found"),
      tiny_errors.SetDetail("user_id", req.ID),
    )
  }

  // ...
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrorStorage

func ErrorStorage() map[int]string

Get global errors storage

func Init

func Init(errors map[int]string)

Store errors globally

Types

type Error

type Error struct {
	Code    int            `json:"code"`
	Message string         `json:"message"`
	Details map[string]any `json:"details"`
	// contains filtered or unexported fields
}

Default type for error data

func (*Error) Error

func (e *Error) Error() string

Error returns the error message.

func (*Error) FormatMessage

func (e *Error) FormatMessage(args ...any)

Formats the message field of the Error using fmt.Sprintf. It replaces any %s and %v specifiers in the message with the provided args.

func (*Error) GetCode

func (e *Error) GetCode() int

Returns the code field of the Error.

func (*Error) GetDetails added in v1.1.6

func (e *Error) GetDetails() map[string]any

Returns the details map of the Error.

func (*Error) GetHTTPMessage

func (e *Error) GetHTTPMessage() string

Returns the HTTP message associated with the error.

func (*Error) GetHTTPStatus

func (e *Error) GetHTTPStatus() int

Returns the HTTP status code associated with the error.

func (*Error) GetMessage

func (e *Error) GetMessage() string

Returns the message field of the Error.

func (*Error) JSON

func (e *Error) JSON() string

Converts the Error to a JSON string.

func (*Error) JSONOrigin

func (e *Error) JSONOrigin() string

Converts the Error to a JSON string.

func (*Error) SetCode

func (e *Error) SetCode(code int)

Sets the code field of the Error.

func (*Error) SetDetail

func (e *Error) SetDetail(name, data string)

Adds a key-value pair to the Details map of the Error. This allows arbitrary additional context to be attached to the Error.

func (*Error) SetHTTPStatus

func (e *Error) SetHTTPStatus(code int)

Sets the HTTP status code and message for the error. The status text is looked up from the provided HTTP status code.

func (*Error) SetMessage

func (e *Error) SetMessage(msg string, format ...any)

Sets the message field of the Error, formatting it with fmt.Sprintf if format args are provided.

type ErrorHandler

type ErrorHandler interface {
	JSON() string
	JSONOrigin() string
	Error() string

	GetHTTPStatus() int
	GetHTTPMessage() string
	GetCode() int
	GetMessage() string
	GetDetails() map[string]any
}

ErrorHandler defines an interface for handling errors that can be converted to JSON. It includes methods to get the HTTP status, message, error code, error message, and convert the error to JSON.

func New

func New(code int, options ...ErrorOption) ErrorHandler

Creates a new ErrorHandler with the given error code and options. The code parameter specifies the error code. If a message is registered for the code in ErrorStorage, it will be used as the default message. The options allow configuring additional details like the message, HTTP status, and custom key-value pairs. Returns the configured ErrorHandler.

type ErrorOption

type ErrorOption func(PropertySetter)

ErrorOption is a function type that can be used to configure an Error. It accepts a PropertySetter func to set properties on the Error being constructed.

func Detail

func Detail(name, data string) ErrorOption

Returns an ErrorOption that adds a key-value pair to the Details map of the Error being constructed. This allows arbitrary additional context to be attached to the Error.

func HTTPStatus

func HTTPStatus(status int) ErrorOption

Returns an ErrorOption that sets the HTTPStatus field of the Error being constructed to the provided status code. This allows associating an HTTP status code with the error.

func Message

func Message(message string, format ...any) ErrorOption

Returns an ErrorOption that sets the message field of the Error being constructed, formatting it with fmt.Sprintf if format args are provided.

func MessageArgs

func MessageArgs(args ...any) ErrorOption

Returns an ErrorOption that formats the message field of the Error being constructed using fmt.Sprintf, replacing any %s and %v specifiers with the provided args.

type PropertySetter

type PropertySetter interface {
	SetMessage(string, ...any)
	FormatMessage(...any)
	SetCode(int)
	SetDetail(name, data string)
	SetHTTPStatus(int)
}

PropertySetter defines methods to set error properties like message, code, details, and HTTP status. This interface allows abstracting away the specific error implementation.

Jump to

Keyboard shortcuts

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