apierrors

package
v1.67.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 5 Imported by: 0

README

Package apierrors

Пакет apierrors предоставляет инструменты для создания и управления структурированными ошибками HTTP-API. Ошибки включают код, сообщение, детали и уровень логирования, а также автоматически сериализуются в JSON для ответов клиентам.

Types

Error

Структура для представления ошибки API. Реализует интерфейс error.

Methods:

NewInternalServiceError(err error) Error

Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с HTTP-статусом 500, бизнесовым кодом 900 и уровнем логирования error.

NewBusinessError(errorCode int, errorMessage string, err error) Error

Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с HTTP-статусом 400, указанным бизнесовым кодом и уровнем логирования warn.

New(httpStatusCode int, errorCode int, errorMessage string, err error) Error

Создает кастомную ошибку с полным контролем параметров.

(e Error) Error() string

Получить строковое представление ошибки.

(e Error) WriteError(w http.ResponseWriter) error

Сериализует ошибку в JSON и записывает в http.ResponseWriter.

(e Error) WithDetails(details map[string]any) Error

Добавить детали информации об ошибке.

(e Error) WithLogLevel(level log.Level) Error

Изменить уровень логирования ошибки.

(e Error) LogLevel() log.Level

Получить текущий уровень логирования ошибки

Usage

Default usage flow
package main

import (
	"context"
	"errors"

	"github.com/txix-open/isp-kit/http/apierrors"
)

type User struct {
	Id   string
	Name string
}

var (
	ErrUserNotFound     = errors.New("user not found")
	ErrUserNotFoundCode = 700
)

type userService interface {
	GetUserById(ctx context.Context, id string) (*User, error)
}

type userController struct {
	svc userService
}

func (c userController) GetUser(ctx context.Context, userId string) (*User, error) {
	result, err := c.svc.GetUserById(ctx, userId)
	switch {
	case errors.Is(err, ErrUserNotFound):
		/* user isn't found so we have to send back specific error code */
		return nil, apierrors.NewBusinessError(ErrUserNotFoundCode, ErrUserNotFound.Error(), err)
	case err != nil:
		/* got some internal error */
		return nil, apierrors.NewInternalServiceError(err)
	default:
		return result, nil
	}
}

Documentation

Overview

Package apierrors provides HTTP error handling with structured error responses. It supports business and internal errors with customizable HTTP status codes, error codes, and logging levels.

Index

Constants

View Source
const (
	// ErrCodeInternal is the default error code for internal service errors.
	ErrCodeInternal = 900
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {
	ErrorCode    int
	ErrorMessage string
	Details      map[string]any `json:",omitempty"`
	// contains filtered or unexported fields
}

Error represents a structured HTTP error with an error code, message, and optional details. It supports custom HTTP status codes, logging levels, and error chaining.

func New

func New(
	httpStatusCode int,
	errorCode int,
	errorMessage string,
	err error,
) Error

New creates a new Error with the specified HTTP status code, error code, message, and cause. The default log level is ErrorLevel.

func NewBusinessError

func NewBusinessError(errorCode int, errorMessage string, err error) Error

NewBusinessError creates a new business error with HTTP 400 status code. It logs at Warn level and is used for client-side validation or business logic errors.

func NewInternalServiceError

func NewInternalServiceError(err error) Error

NewInternalServiceError creates a new internal service error with HTTP 500 status code. It logs at Error level and wraps the provided cause error.

func (Error) Error

func (e Error) Error() string

Error returns a formatted string representation of the error.

func (Error) LogLevel

func (e Error) LogLevel() log.Level

LogLevel returns the logging level associated with this error.

func (Error) WithDetails

func (e Error) WithDetails(details map[string]any) Error

WithDetails adds additional context details to the error.

func (Error) WithLogLevel

func (e Error) WithLogLevel(level log.Level) Error

WithLogLevel sets the logging level for this error.

func (Error) WriteError

func (e Error) WriteError(w http.ResponseWriter) error

WriteError writes the error as a JSON response to the http.ResponseWriter. It sets the Content-Type header to application/json and the appropriate HTTP status code.

Jump to

Keyboard shortcuts

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