errs

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2023 License: MIT Imports: 8 Imported by: 0

README

Package errs

Package errs provides error codes and error handling functionalities.

Overview

The errs package defines common error codes and provides a way to handle and generate error responses. It includes functionalities for creating error objects with error codes, messages, timestamps, and additional information. The package also maps the error codes to their corresponding HTTP status codes for convenient handling in web applications.

Installation

To use the errs package, you can import it in your Go project:

import "github.com/thirathawat/errs"

Make sure to run go get to retrieve the package:

go get github.com/thirathawat/errs

Usage

Error Codes

The package defines the following error codes:

  • CodeBadRequest: Represents a bad request error.
  • CodeUnauthorized: Represents an unauthorized error.
  • CodeForbidden: Represents a forbidden error.
  • CodeNotFound: Represents a not found error.
  • CodeGone: Represents a gone error.
  • CodeTooManyRequests: Represents a too many requests error.
  • CodeInternalServerError: Represents an internal server error.
  • CodeNotImplemented: Represents a not implemented error.
  • CodeServiceUnavailable: Represents a service unavailable error.
Creating Errors

To create a new error, use the New function provided by the package:

err := errs.New(errs.CodeBadRequest, "Invalid request")

You can also provide additional options when creating an error. For example, you can include additional information or log the error:

err := errs.New(errs.CodeInternalServerError, "Internal server error",
    errs.WithInfo(map[string]interface{}{"requestID": "abc123"}),
    errs.WithLogErr(innerError),
)
Handling Errors

The package provides a convenient function ResponseError to handle errors in a Gin HTTP handler:

func MyHandler(c *gin.Context) {
    err := // Some operation that may return an error
    if err != nil {
        errs.ResponseError(c, err)
        return
    }

    // Handle successful case
    ...
}

The ResponseError function checks if the provided error is an errs.Error object. If it is, it returns a JSON response with the error information, including the error code and message. Otherwise, it returns a generic internal server error response.

Validation Errors

The package includes functionality to handle validation errors. If you have a validation error returned by a validation library, you can convert it to an errs.Error object using the InvalidStructError function:

validationErr := // Some validation error
err := errs.InvalidStructError(validationErr)

This function converts the validation error into a structured error with the appropriate error code, message, and additional information about the validation errors.

License

This package is licensed under the MIT License. See the LICENSE file for more information.

Documentation

Overview

Package errs provides error codes and error handling.

Index

Constants

This section is empty.

Variables

Common errors.

Functions

func ResponseError

func ResponseError(c *gin.Context, err error)

ResponseError returns an error response.

Types

type Code

type Code string

Code represents an error code.

const (
	CodeBadRequest      Code = "BAD_REQUEST"
	CodeUnauthorized    Code = "UNAUTHORIZED"
	CodeForbidden       Code = "FORBIDDEN"
	CodeNotFound        Code = "NOT_FOUND"
	CodeGone            Code = "GONE"
	CodeTooManyRequests Code = "TOO_MANY_REQUESTS"

	CodeInternalServerError Code = "INTERNAL_SERVER_ERROR"
	CodeNotImplemented      Code = "NOT_IMPLEMENTED"
	CodeServiceUnavailable  Code = "SERVICE_UNAVAILABLE"
)

Error codes.

func (Code) String

func (c Code) String() string

String returns the string representation of the error code.

type Error

type Error struct {
	// Code is the error code.
	Code Code `json:"code"`

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

	// Info is additional information about the error.
	Info map[string]interface{} `json:"info,omitempty"`

	// Timestamp is the time when the error occurred.
	Timestamp time.Time `json:"timestamp"`
}

Error represents an error.

func InvalidStructError

func InvalidStructError(err error) *Error

InvalidStructError returns a new error for an invalid struct.

func New

func New(code Code, msg string, opts ...Option) *Error

New returns a new error.

func (*Error) Error

func (e *Error) Error() string

Error returns the string representation of the error.

func (*Error) HTTPStatusCode

func (e *Error) HTTPStatusCode() int

HTTPStatusCode returns the HTTP status code for the error.

type Option

type Option func(*option)

Option represents an option for an error.

func WithInfo

func WithInfo(info map[string]interface{}) Option

WithInfo sets the info option.

func WithLogErr

func WithLogErr(err error) Option

WithLogErr sets the log error option.

Jump to

Keyboard shortcuts

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