# 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),
)
}
// ...
}
# Functions
Returns an ErrorOption that adds a key-value pair to the Details map of the Error being constructed.
Get global errors storage.
Returns an ErrorOption that sets the HTTPStatus field of the Error being constructed to the provided status code.
Store errors globally.
Returns an ErrorOption that sets the message field of the Error being constructed, formatting it with fmt.Sprintf if format args are provided.
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.
Creates a new ErrorHandler with the given error code and options.
# Interfaces
ErrorHandler defines an interface for handling errors that can be converted to JSON.
PropertySetter defines methods to set error properties like message, code, details, and HTTP status.
# Type aliases
ErrorOption is a function type that can be used to configure an Error.