apierrors

package
v1.67.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 7 Imported by: 0

README

Package apierrors

Пакет apierrors предоставляет структурированный формат ошибок для gRPC-сервисов с поддержкой кодов ошибок, деталей, уровней логирования и интеграции с gRPC-статусами. Позволяет единообразно обрабатывать бизнес-ошибки и технические сбои.

Types

Error

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

Methods:

NewInternalServiceError(err error) Error

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

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

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

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

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

(e Error) Error() string

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

(e Error) GrpcStatusError() error

Конвертирует ошибку в gRPC-сообщение с сериализованными деталями об ошибке в формате JSON.

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

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

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

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

(e Error) LogLevel() log.Level

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

Functions

FromError(err error) *Error

Извлекает структурированную бизнесовую ошибку из gRPC-сообщения спрятанного под интерфейс error.

Usage

Default usage flow
package main

import (
	"context"
	"errors"

	"github.com/txix-open/isp-kit/grpc/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 structured error handling for gRPC services. It defines custom error types with business error codes, gRPC status codes, and structured details for comprehensive error reporting.

Errors can be converted to gRPC status errors with JSON-encoded details, enabling rich error information to be transmitted across service boundaries.

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 error with business and gRPC status codes. Includes optional details for field-specific errors and a configurable log level. Implements the GrpcError interface for conversion to gRPC status errors.

Fields:

  • ErrorCode: Business-level error code (e.g., 400 for bad request)
  • ErrorMessage: Human-readable error message
  • Details: Optional map of field-specific error details
  • grpcStatusCode: gRPC status code (e.g., codes.InvalidArgument)
  • cause: Underlying error cause
  • level: Log level for error logging

func FromError

func FromError(err error) *Error

FromError extracts an Error from a gRPC status error. Returns nil if the error is not a gRPC status error or if the details cannot be parsed. Useful for checking if an error originated from a remote service.

func New

func New(
	grpcStatusCode codes.Code,
	errorCode int,
	errorMessage string,
	err error,
) Error

New creates a new Error with the specified parameters. Sets default log level to Error.

func NewBusinessError

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

NewBusinessError creates a new business validation error. Uses gRPC status code InvalidArgument and the specified error code. Sets log level to Warn.

func NewInternalServiceError

func NewInternalServiceError(err error) Error

NewInternalServiceError creates a new internal service error. Uses gRPC status code Internal and business error code 900. Sets log level to Error.

func (Error) Error

func (e Error) Error() string

Error returns a string representation of the error. Includes error code, message, and underlying cause.

func (Error) GrpcStatusError

func (e Error) GrpcStatusError() error

GrpcStatusError converts the Error to a gRPC status error. Serializes the error to JSON and attaches it as gRPC status details. Returns an error if JSON marshaling or status creation fails.

func (Error) LogLevel

func (e Error) LogLevel() log.Level

LogLevel returns the log level for this error.

func (Error) WithDetails

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

WithDetails sets the error details map. Returns the Error for method chaining.

func (Error) WithLogLevel

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

WithLogLevel sets the log level for this error. Returns the Error for method chaining.

Jump to

Keyboard shortcuts

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