errkratos

package module
v0.0.31 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 1 Imported by: 2

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

errkratos

Advanced Kratos error handling package with type-safe operations and nil interface trap prevention.


CHINESE README

中文说明

Main Features

🎯 Type-Safe Error Handling: Simplified API to manipulate Kratos errors without naming conflicts ⚡ Safe Error Handling: Solves Go's notorious (*T)(nil) != nil trap through intelligent adaptation 🔄 Testing Integration: Complete testify/assert and testify/require helpers to test Kratos errors

Installation

go get github.com/orzkratos/errkratos

Usage

Basic Error Handling
import "github.com/orzkratos/errkratos"

// Type-safe error conversion
err := someFunction()
if erk, ok := errkratos.As(err); ok {
    fmt.Printf("Kratos error: %s (code: %d)\n", erk.Reason, erk.Code)
}

// Error comparison
erk1 := errors.BadRequest("INVALID_INPUT", "missing field")
erk2 := errors.BadRequest("INVALID_INPUT", "wrong format")
if errkratos.Is(erk1, erk2) {
    // Same error type (reason and code match)
}

// Convert generic error to Kratos error
erk := errkratos.From(err)
Concise Error Creation (newerk)
import "github.com/orzkratos/errkratos/newerk"

// Configure reason code field name to store enum numeric value
newerk.SetReasonCodeFieldName("numeric_reason_code_enum")

// Create type-safe error with enum
erk := newerk.NewError(404, ErrorReason_USER_NOT_FOUND, "user %d not found", userID)

// Check error type
if newerk.IsError(err, ErrorReason_USER_NOT_FOUND, 404) {
    // Handle user not found error
}
Testing with Assert
import "github.com/orzkratos/errkratos/must/erkassert"

func TestSomething(t *testing.T) {
    var erk *errors.Error
    
    // Assert no error (handles nil interface with safe checks)
    erkassert.NoError(t, erk)
    
    // Assert error exists
    erk = errors.InternalServer("SERVER_ERROR", "database failed")
    erkassert.Error(t, erk)
    
    // Assert error equivalence
    expected := errors.BadRequest("INVALID_INPUT", "test")
    erkassert.Is(t, expected, erk)
}
Testing with Require
import "github.com/orzkratos/errkratos/must/erkrequire"

func TestCritical(t *testing.T) {
    var erk *errors.Error

    // Require no error (stops test at once if error exists)
    erkrequire.NoError(t, erk)

    // Continue when no error...
}
Production Error Enforcement
import "github.com/orzkratos/errkratos/must/erkmust"

func criticalOperation() {
    erk := doSomethingImportant()
    
    // Panic if error exists (with structured logging)
    erkmust.Done(erk)

    // Use Must (same function, different name)
    erkmust.Must(erk)
}

Package Structure

errkratos/
├── errors.go           # Core API (As, Is, From)
├── newerk/             # Concise error creation API
├── erkadapt/           # Nil interface adaptation
├── must/               # Testing and enforcement tools
│   ├── erkassert/      # testify/assert helpers
│   ├── erkrequire/     # testify/require helpers
│   └── erkmust/        # Production panic utilities
└── internal/
    └── errorspb/       # Example error definitions

What Makes errkratos Worth Using?

The Nil Interface Issue

Go has a known issue where a typed nil value doesn't match nil when converted to interface:

var erk *errors.Error = nil
var err error = erk
fmt.Println(erk == nil)  // true
fmt.Println(err == nil)  // false (!!)

This causes issues in error handling. errkratos solves this through intelligent adaptation in each function.

Clean Naming

The Erk type alias avoids import conflicts between standard errors package and Kratos errors:

// Instead of this confusion:
import (
    stderrors "errors"
    "github.com/go-kratos/kratos/v2/errors"
)

// Just use:
import "github.com/orzkratos/errkratos"
// And work with errkratos.Erk

More Projects

  • ebzkratos - Error type that doesn't implement error interface

📄 License

MIT License. See LICENSE.


🤝 Contributing

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Found a mistake? Open an issue on GitHub with reproduction steps
  • 💡 Have a feature idea? Create an issue to discuss the suggestion
  • 📖 Documentation confusing? Report it so we can improve
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize through reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes and use significant commit messages
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


GitHub Stars

Stargazers

Documentation

Overview

Package errkratos: Advanced Kratos error handling utilities with type-safe operations Provides simplified API for Kratos error manipulation with naming conflict avoidance Features streamlined error conversion, comparison, and type assertion functions Optimized for production Kratos applications with clean error handling patterns

errkratos: 高级 Kratos 错误处理工具,提供类型安全操作 为 Kratos 错误操作提供简化的 API,避免命名冲突 具有简化的错误转换、比较和类型断言函数 为生产环境 Kratos 应用的清晰错误处理模式进行了优化

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func As

func As(err error) (erk *errors.Error, ok bool)

As performs type-safe conversion from generic error to Kratos-specific error type Returns the converted error and success flag for safe error handling patterns Eliminates need for type assertions in error processing workflows Optimized for high-throughput error handling in production services

As 执行从通用 error 到 Kratos 特定错误类型的类型安全转换 返回转换后的错误和成功标志,用于安全的错误处理模式 消除错误处理工作流中类型断言的需求 为生产服务中的高吞吐量错误处理进行了优化

func From

func From(err error) *errors.Error

From provides concise alias for FromError to reduce function name length Same as FromError but with compact syntax for frequent usage Optimizes coding experience when working with intensive error handling

From 为 FromError 提供简洁别名,减少函数名长度 为频繁使用提供与 FromError 相同功能但更紧凑的语法 在密集错误处理场景中优化编码体验

func FromError

func FromError(err error) *errors.Error

FromError converts generic error interface to Kratos error with intelligent handling Wraps standard errors into Kratos error format when needed Preserves existing Kratos error metadata and context information Provides unified error handling interface for mixed error sources

FromError 将通用 error 接口转换为 Kratos 错误,具有智能处理 需要时将标准错误包装为 Kratos 错误格式 保留现有的 Kratos 错误元数据和上下文信息 为混合错误源提供统一的错误处理接口

func Is

func Is(erk1 *errors.Error, erk2 *errors.Error) bool

Is compares two Kratos errors for equivalence with nil-safe operation Performs intelligent comparison based on error reason and code matching Handles nil cases with safe checks to prevent runtime panics Essential for error classification and handling in service code

Is 比较两个 Kratos 错误的等价性,具有 nil 安全操作 基于错误原因和代码匹配执行智能比较 通过安全检查处理 nil 情况,防止运行时 panic 对于服务代码中的错误分类和处理至关重要

Types

type Erk

type Erk = errors.Error

Erk provides simplified type alias to avoid naming conflicts with standard packages Concise naming reduces code verbosity and maintains semantic precision Prevents import conflicts between standard errors package and Kratos errors

Erk 为 errors.Error 提供简化的类型别名,避免与标准库命名冲突 简洁命名减少代码冗长度,同时保持语义精确性 防止标准 errors 包与 Kratos errors 包之间的导入冲突

Directories

Path Synopsis
Package erkadapt: Critical Go interface adaptation utilities to handle nil pointers Provides sophisticated error interface conversion with correct nil handling semantics Solves Go's notorious (*T)(nil) != nil interface trap through intelligent adaptation Essential when integrating with external packages expecting standard error interface
Package erkadapt: Critical Go interface adaptation utilities to handle nil pointers Provides sophisticated error interface conversion with correct nil handling semantics Solves Go's notorious (*T)(nil) != nil interface trap through intelligent adaptation Essential when integrating with external packages expecting standard error interface
internal
must
erkassert
Package erkassert: Advanced testify/assert wrapper for Kratos error testing Provides type-safe assertion functions specifically designed for Kratos error validation Solves nil interface problems through intelligent error adaptation mechanisms Optimized for comprehensive test coverage in Kratos-based microservice architectures
Package erkassert: Advanced testify/assert wrapper for Kratos error testing Provides type-safe assertion functions specifically designed for Kratos error validation Solves nil interface problems through intelligent error adaptation mechanisms Optimized for comprehensive test coverage in Kratos-based microservice architectures
erkmust
Package erkmust: Production-grade error enforcement utilities for Kratos applications Provides fast-exit error checking with structured logging and immediate panic termination Implements rigorous error validation for mission-critical production code paths Optimized for zero-error-tolerance Kratos services with strict requirements
Package erkmust: Production-grade error enforcement utilities for Kratos applications Provides fast-exit error checking with structured logging and immediate panic termination Implements rigorous error validation for mission-critical production code paths Optimized for zero-error-tolerance Kratos services with strict requirements
erkrequire
Package erkrequire: Advanced testify/require wrapper for strict Kratos error validation Provides fail-fast assertion functions with immediate test termination on failure Implements intelligent nil interface handling for reliable error state verification Optimized for critical path testing in production Kratos service validation workflows
Package erkrequire: Advanced testify/require wrapper for strict Kratos error validation Provides fail-fast assertion functions with immediate test termination on failure Implements intelligent nil interface handling for reliable error state verification Optimized for critical path testing in production Kratos service validation workflows

Jump to

Keyboard shortcuts

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