Skip to content

About

A lib for using trycatch in Go!

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

English | 中文

GoTryCatch

Version Go

A type-safe exception handling library based on Go generics that brings try-catch-like capabilities to Go.

Features

  • 🎯 Type-safe: Uses Go generics to ensure type-safe exception handling
  • 🔗 Full chaining: Go 1.27 generic methods keep Catch / CatchAs on the block, so the whole pipeline reads top to bottom without type arguments
  • 🏷️ Multiple error types: Built-in common error types (validation, database, network, business logic, auth, config, rate limit)
  • 📊 Structured output: All errors support ToMap() and ToJSON() for easy parsing by agents/logs
  • 🔍 Rich context: Errors include file, line, function, timestamp, and stack trace
  • 🔄 Cleanup: Run registers Cleanup with the call. Classic Finally runs only when you call it, and a panicking Catch handler never reaches a later Finally
  • 🎁 Result pipelines: TryWithResult supports Then / ThenErr / Recover / RecoverAs in addition to OnSuccess/OnError/OrElse
  • 🧰 Reusable policies: Policy packages a clause set once and runs it from any entry point
  • 🔬 Request-scoped debugging: Scope keeps debug switches and cleanups out of process-wide state
  • 🐛 Debug mode: Optional debug logging for type matching issues
  • 📦 Zero dependency: Pure Go implementation, no external dependencies
  • 🚀 High performance: Built on Go's panic/recover with minimal overhead

Important Note

Go 1.27+ required. Go 1.27 generic methods are what make tb.Catch(handler) possible; the v2 functional forms (Catch[T](tb, handler), CatchWithResult, CatchAsWithResult) are gone in v3. See Migrating from v2.

Semantic Boundaries

Read these before relying on this library in production:

  1. A panic inside a Catch handler propagates immediately and skips any later Finally call. The chain is plain function calls, not a deferred block. Keep handler bodies non-panicking, or wrap them in their own Try.
  2. A panic inside Finally replaces the original error — same as Go's native defer. If Finally must run fallible cleanup, guard it with its own recover.
  3. Try does not catch panics from goroutines started inside fn. recover only works within the same goroutine; an unhandled panic in a child goroutine still crashes the process.
  4. Catch and On are exact type assertions, not errors.As. panic(&err) does not match Catch(func(Err)) or On(func(Err)). CatchAs / OnAs / MapAs penetrate fmt.Errorf("...: %w", err) wrapping, and E and *E are different targets. errtypes constructors return values, so write the value type in the clause. If nothing handles a clause that differs only by pointer depth (including inside %w or errors.Join chains for OnAs/MapAs), Run returns *NearMissError (its Unwrap is the original error). Any swallows that hint; turn on SetDebug to log it.
  5. Run cleanups all run, LIFO, including when one of them panics or a handler panics. A cleanup panic is returned as Run's error and joined with an unhandled business error when both exist. A handler panic propagates after cleanups as *HandlerPanic: Value is what the handler panicked with, Original is the panic it received, Stack() holds the handler panic trace, and Unwrap reaches the original error (and the cleanup error, when there is one). Panics in a child goroutine are never captured.
  6. Finally re-panics the original value, so the stack of that panic starts at Finally. Call Err before Finally to read the stack captured at the original panic site. OrElse / OrElseGet replace any panic with the default, handled or not. Use Result or Run1 when the error must stay visible.

Installation

go get github.com/linkerlin/gotrycatch/v3

The v3 Way: Generic Methods

Go 1.27 lets a method declare its own type parameters, so the chain no longer breaks. No explicit type arguments, no tb = reassignment, and IDE completion sees Catch after tb.:

gotrycatch.Try(func() { doWork() }).
    CatchAs(func(e errtypes.ValidationError) { /* errors.As, unwraps %w */ }).
    Catch(func(s string) { /* exact type */ }).
    CatchAny(func(v interface{}) { /* fallback */ }).
    Finally(func() { /* cleanup */ })

TryWithResult gains value transformation and recovery:

displayName, err := gotrycatch.TryWithResult(func() []byte { return mustRead(path) }).
    Then(func(raw []byte) User { return mustParseUser(raw) }).
    Then(func(u User) string { return u.DisplayName }).
    RecoverAs(func(e errtypes.ConfigError) string { return "guest" }).
    Result()
  • Then / ThenErr: transform T into U; an unhandled panic short-circuits the rest of the chain. A panic inside the function is captured as the new block's error.
  • Recover / RecoverAs: turn an unhandled panic into a replacement T; unlike Catch, the value is not thrown away. Recover is exact, RecoverAs unwraps.
  • ErrorAs[E]() (E, bool): one-line extraction with errors.As semantics, on both block types.
  • ValueAs[T]() (T, bool): exact extraction of a non-error panic value.

Reusable policies

var apiPolicy = gotrycatch.NewPolicy().
    MapAs(func(e errtypes.ValidationError) error { return httpErr(400, e) }).
    MapAs(func(e errtypes.AuthError) error { return httpErr(401, e) }).
    MapAs(func(e errtypes.RateLimitError) error { return httpErr(429, e) })

user, err := apiPolicy.Run1(func() User { return loadUser(id) })

A Policy is immutable once built: share one across handlers, no per-request allocation of the clause slice.

Request-scoped diagnostics

scope := gotrycatch.NewScope(
    gotrycatch.WithDebug(true),
    gotrycatch.WithLogger(reqLogger), // *slog.Logger
    gotrycatch.WithCleanup(func() { releaseRequestResources() }),
)

res, err := scope.Run1(func() Order {
    cfg := scope.Must(loadConfig())
    return buildOrder(cfg)
})

Scope never touches the process-wide SetDebug flag, so parallel tests and per-request traces stay isolated.

The Run Entry Point

Run is the recommended entry point. It is one call, impossible to forget cleanup, and results flow through ordinary Go error handling:

import (
    "fmt"

    "github.com/linkerlin/gotrycatch/v3"
    "github.com/linkerlin/gotrycatch/v3/errtypes"
)

func loadUser(id string) error {
    err := gotrycatch.Run(func() { queryUser(id) },
        // errors.As semantics: matches through fmt.Errorf("%w", ...) wrappers
        gotrycatch.OnAs(func(e errtypes.DatabaseError) {
            retry(id)
        }),
        gotrycatch.On(func(e errtypes.RateLimitError) {
            wait(e.RetryAfter)
        }),
        // always runs, LIFO, even if a handler panics
        gotrycatch.Cleanup(func() { conn.Close() }),
    )
    if err != nil {
        return fmt.Errorf("load user %s: %w", id, err)
    }
    return nil
}

Why it is hard to misuse:

  • Unhandled panics come back as error — silently swallowing is structurally impossible. Error panics pass through unchanged (so errors.Is/As work end-to-end); other values are wrapped in *PanicError.
  • Cleanup always runs — declared inline, LIFO. A cleanup panic comes back on the returned error and does not drop an unhandled business error.
  • Clauses are ordered values — no method/function chaining rules to memorize.
  • Run1 covers return values: v, err := gotrycatch.Run1(fn, clauses...).

Sentinel errors use OnIs (or MapIs to translate), which do not consume other errors. To turn a matched panic into the error you return, use MapAs or MapIs:

err := gotrycatch.Run(func() { open(path) },
    gotrycatch.OnIs(os.ErrNotExist, func(error) { useDefault() }),
    gotrycatch.MapIs(os.ErrPermission, func(e error) error {
        return fmt.Errorf("permission denied: %w", e)
    }),
    gotrycatch.MapAs(func(e errtypes.DatabaseError) error {
        return fmt.Errorf("query: %w", e)
    }),
)

OnAs(func(e error)) and On(func(e error)) match every error and mark it handled. Put OnIs/MapIs before such a clause when only one sentinel should be consumed.

Quick Start (chain API)

Run remains the one-call entry point; the chain API is fully supported:

package main

import (
    "fmt"

    "github.com/linkerlin/gotrycatch/v3"
    "github.com/linkerlin/gotrycatch/v3/errtypes"
)

func main() {
    gotrycatch.Try(func() {
        // Code that may panic
        gotrycatch.Throw(errtypes.NewValidationError("email", "invalid format", 1001))
    }).Catch(func(err errtypes.ValidationError) {
        fmt.Printf("Validation error: %s (field: %s, code: %d)\n", err.Message, err.Field, err.Code)
    }).Finally(func() {
        fmt.Println("Cleanup done")
    })
}

TryWithResult - Functions with return values

// Execute function that returns a value
tb := gotrycatch.TryWithResult(func() int {
    return computeValue()
})

// Success callback
tb.OnSuccess(func(result int) {
    fmt.Println("Result:", result)
})

// Error callback
tb.OnError(func(err interface{}) {
    fmt.Println("Error:", err)
})

// Get result with default value
result := tb.OrElse(0)

// Or lazy evaluation of default
result := tb.OrElseGet(func() int { return computeDefault() })

For transformation and recovery, use the v3 pipeline methods:

result, err := gotrycatch.TryWithResult(func() int { return computeValue() }).
    Then(func(n int) string { return strconv.Itoa(n) }).
    Recover(func(err errtypes.ConfigError) string { return "default" }).
    Result()

Handling multiple error types

gotrycatch.Try(func() {
    processUserData()
}).Catch(func(err errtypes.ValidationError) {
    fmt.Printf("Validation failed: %s\n", err.Message)
}).Catch(func(err errtypes.DatabaseError) {
    fmt.Printf("Database error: %s on table %s\n", err.Operation, err.Table)
}).Catch(func(err errtypes.NetworkError) {
    if err.Timeout {
        fmt.Printf("Network timeout: %s\n", err.URL)
    } else {
        fmt.Printf("Network error %d: %s\n", err.StatusCode, err.URL)
    }
}).CatchAny(func(err interface{}) {
    fmt.Printf("Unknown error: %v\n", err)
}).Finally(func() {
    fmt.Println("Processing done")
})

State query and debugging

tb := gotrycatch.Try(func() {
    riskyOperation()
})

// Query state
if tb.HasError() {
    fmt.Printf("Error type: %s\n", tb.GetErrorType())
    fmt.Printf("Error value: %v\n", tb.GetError())
}

if !tb.IsHandled() {
    // Decide how to handle based on error type
    switch tb.GetErrorType() {
    case "errtypes.ValidationError":
        // Handle validation error
    default:
        tb = tb.CatchAny(func(err interface{}) {
            logUnknownError(err)
        })
    }
}

// Enable debug mode to trace type matching
gotrycatch.SetDebug(true)

Structured error output (Agent-friendly)

tb := gotrycatch.Try(func() { processOrder() })
tb.Catch(func(err errtypes.BusinessLogicError) {
    // JSON output for logging/agents
    jsonData, _ := err.ToJSON()
    log.Printf("ERROR: %s", string(jsonData))
    // Output: {"type":"BusinessLogicError","rule":"inventory_check","details":"Out of stock","file":"main.go","line":42,"function":"processOrder","timestamp":"2024-01-15T10:30:00Z","stack":[...]}
})

// Or pull a typed error out in one line (errors.As semantics)
if ve, ok := tb.ErrorAs[errtypes.ValidationError](); ok {
    fmt.Println(ve.Field, ve.Code)
}

Assertion helpers

// Assert condition, throw error if false
gotrycatch.Assert(value != "", errtypes.NewValidationError("value", "cannot be empty", 1001))

// Assert no error, wrap and throw if error exists
gotrycatch.AssertNoError(err, "database operation failed")

Built-in Error Types

All error types include: File, Line, Function, Timestamp, Stack

Type Specific Fields Constructor Use Case
ValidationError Field, Message, Code NewValidationError(field, message, code) Data validation errors
DatabaseError Operation, Table, Cause NewDatabaseError(operation, table, cause) Database operation errors
NetworkError URL, StatusCode, Timeout, Cause NewNetworkError(url, code) / .WithCause(err) HTTP errors
NetworkError URL, Timeout, Cause NewNetworkTimeoutError(url) / .WithCause(err) Network timeouts
BusinessLogicError Rule, Details NewBusinessLogicError(rule, details) Business rule violations
ConfigError Key, Value, Reason, Cause NewConfigError(key, value, reason) / .WithCause(err) Configuration errors (redact secret Values)
AuthError Operation, User, Reason, Cause NewAuthError(operation, user, reason) / .WithCause(err) Authentication/authorization errors
RateLimitError Resource, Limit, Current, RetryAfter NewRateLimitError(resource, limit, current, retryAfter) Rate limiting errors

Error methods

var err errtypes.ValidationError

err.Error()       // string - Full error description with location
err.ToMap()       // map[string]interface{} - Structured data
err.ToJSON()      // ([]byte, error) - JSON output
err.MarshalJSON() // ([]byte, error) - json.Marshaler, identical to ToJSON()
err.LogValue()    // slog.Value - slog.LogValuer structured output (Go 1.21+ stdlib)
err.Unwrap()      // error - Underlying error (DatabaseError and WithCause errors)
err.Is(target)    // bool - Error matching

API Reference

Core Functions

Function/Method Signature Description
Run func Run(fn func(), clauses ...Clause) error v2 Idiomatic clause-based execution; returns unhandled panics as error
Run1 func Run1[T any](fn func() T, clauses ...Clause) (T, error) v2 Run with a return value
On[E] func On[E any](handler func(E)) Clause v2 Clause: exact-type match (Catch semantics)
OnAs[E] func OnAs[E error](handler func(E)) Clause v2 Clause: errors.As match, penetrates %w wrapping. E and *E are distinct
OnIs func OnIs(target error, handler func(error)) Clause v2.2 Clause: errors.Is match; other errors fall through
Map[E] func Map[E any](handler func(E) error) Clause v2.2 Exact match; a non-nil return becomes Run's error
MapAs[E] func MapAs[E error](handler func(E) error) Clause v2.2 errors.As match; a non-nil return becomes Run's error
MapIs func MapIs(target error, handler func(error) error) Clause v2.3 errors.Is match; a non-nil return becomes Run's error
Any func Any(handler func(interface{})) Clause v2 Clause: fallback for any panic
Cleanup func Cleanup(fn func()) Clause v2.2 Always runs, LIFO; a panic here is returned as an error
Try func Try(fn func()) *TryBlock Execute function and capture any panic
(*TryBlock).Catch[E] func (tb *TryBlock) Catch[E any](handler func(E)) *TryBlock v3 Handle panics of exact type E; chainable
(*TryBlock).CatchAs[E] func (tb *TryBlock) CatchAs[E error](handler func(E)) *TryBlock v3 errors.As match. E and *E are distinct targets
(*TryBlock).CatchAny func (tb *TryBlock) CatchAny(handler func(interface{})) *TryBlock Handle any unhandled panic
(*TryBlock).ErrorAs[E] func (tb *TryBlock) ErrorAs[E error]() (E, bool) v3 Typed extraction with errors.As semantics
(*TryBlock).ValueAs[T] func (tb *TryBlock) ValueAs[T any]() (T, bool) v3 Exact extraction of a panic value
Finally func (tb *TryBlock) Finally(fn func()) Execute cleanup code

Wrapper Error Types (v2)

Type Key Fields / Methods Description
PanicError Value, Unwrap(), Stack() []string Wraps non-error panics in Run/Err(); lazy stack capture
HandlerPanic Value, Original, Cleanup, Unwrap(), Stack() []string Propagated when a clause handler panics; cleanups still run
NearMissError Err, Hint, Unwrap() Attached when an unhandled panic matches a clause type only with different pointer depth

TryBlock State Query

Method Return Type Description
HasError() bool Whether a panic was captured
GetError() interface{} Get the panic value
Err() error v2 Panic bridged to error (errors.Is/As-ready; non-error panics become *PanicError)
GetErrorType() string Get error type name (e.g., "errtypes.ValidationError")
CanonicalErrorType() string v2 Pointer-free short type name (e.g., "ValidationError")
IsHandled() bool Whether error was handled
String() string Friendly string representation

TryWithResult

Function/Method Signature Description
TryWithResult func TryWithResult[T any](fn func() T) *TryBlockWithResult[T] Execute function with return value
Catch[E] func (tb *TryBlockWithResult[T]) Catch[E any](handler func(E)) *TryBlockWithResult[T] v3 Typed catch; infers E from the handler
CatchAs[E] func (tb *TryBlockWithResult[T]) CatchAs[E error](handler func(E)) *TryBlockWithResult[T] v3 errors.As match
CatchAny func (tb *TryBlockWithResult[T]) CatchAny(handler func(interface{})) *TryBlockWithResult[T] Catch any for TryWithResult
Then[U] func (tb *TryBlockWithResult[T]) Then[U any](fn func(T) U) *TryBlockWithResult[U] v3 Transform the value; short-circuits on an unhandled panic
ThenErr[U] func (tb *TryBlockWithResult[T]) ThenErr[U any](fn func(T) (U, error)) *TryBlockWithResult[U] v3 Transform with a fallible function
Recover[E] func (tb *TryBlockWithResult[T]) Recover[E any](fn func(E) T) *TryBlockWithResult[T] v3 Produce a replacement T from an exact-type panic
RecoverAs[E] func (tb *TryBlockWithResult[T]) RecoverAs[E error](fn func(E) T) *TryBlockWithResult[T] v3 Recover through %w wrapping
ErrorAs[E] func (tb *TryBlockWithResult[T]) ErrorAs[E error]() (E, bool) v3 Typed extraction with errors.As semantics
GetResult() T Get the result value
OnSuccess func (tb *TryBlockWithResult[T]) OnSuccess(fn func(T)) *TryBlockWithResult[T] Callback on success
OnError func (tb *TryBlockWithResult[T]) OnError(fn func(interface{})) *TryBlockWithResult[T] Callback on error
OrElse func (tb *TryBlockWithResult[T]) OrElse(defaultValue T) T Default on any panic, handled or not; the error is discarded
OrElseGet func (tb *TryBlockWithResult[T]) OrElseGet(supplier func() T) T Lazy default on any panic; the error is discarded
Result func (tb *TryBlockWithResult[T]) Result() (T, error) Value plus Err for an unhandled panic

Policy and Scope (v3)

Function/Method Signature Description
NewPolicy func NewPolicy(clauses ...Clause) *Policy Build a reusable clause set
(*Policy).On/OnAs/OnIs func (p *Policy) On[E any](handler func(E)) *Policy (and siblings) Chainable rule builders
(*Policy).Map/MapAs/MapIs/Any/Cleanup chainable Same clauses as the package-level constructors
(*Policy).Run func (p *Policy) Run(fn func()) error Execute under the policy
(*Policy).Run1[T] func (p *Policy) Run1[T any](fn func() T) (T, error) Execute with an inferred result type
NewScope func NewScope(opts ...ScopeOption) *Scope Request/test-local diagnostics
WithDebug func WithDebug(enabled bool) ScopeOption Scope-only debug switch
WithLogger func WithLogger(logger *slog.Logger) ScopeOption Scope diagnostic sink
WithCleanup func WithCleanup(fn func()) ScopeOption Runs after every scope Run/Run1
(*Scope).Try/TryWithResult/Run/Run1/Must generic methods Scoped variants of the core API

Debug & Assertions

Function Signature Description
SetDebug func SetDebug(enabled bool) Enable/disable debug logging (process-wide)
SetDebugOutput func SetDebugOutput(w io.Writer) Debug writer; nil restores stderr (process-wide)
IsDebug func IsDebug() bool Check debug mode status
Throw func Throw(err interface{}) Throw an exception (panic)
Assert func Assert(condition bool, err interface{}) Assert condition, throw if false
AssertNoError func AssertNoError(err error, msg string) Assert no error, throw with message if error
Must func Must[T any](v T, err error) T v2.4 Return v if err == nil, else Throw(err)
MustMsg func MustMsg[T any](v T, err error, msg string) T v2.4 Return v if err == nil, else wrap with msg and Throw

Best Practices

  1. Order Catch blocks by specificity: Most specific types first, generic types later
  2. Prefer Run and Cleanup for new code: Classic Finally runs only when called
  3. Use predefined error types: Prefer structured errors over raw strings/numbers
  4. Use CatchAny as fallback: Handle unexpected error types gracefully
  5. Enable debug mode for troubleshooting: Use SetDebug(true) when type matching doesn't work as expected
  6. Use ToJSON for logging: Structured output is easier to parse and analyze

Performance

Measured with go test -run '^$' -bench . -benchmem -benchtime=200ms ./... (go1.26.5 windows/amd64, i9-13900HX, indicative only):

Scenario ns/op B/op allocs/op
Error return (idiomatic baseline) ~0.16 0 0
Raw recover, no panic ~2.2 0 0
Run1, no panic (pre-built clauses) ~22 0 0
Run, no panic (pre-built clauses) ~24 0 0
Run, no panic (inline clauses) ~426 96 5
Try, no panic ~30 48 1
TryWithResult + OrElse, no panic ~61 64 1
Raw recover, panic path (error) ~177 0 0
Run + panic + On hit (string) ~402 24 1
Run + error panic unhandled ~483 24 1
Try + error panic + Catch hit ~543 48 1
Run + non-error unhandled panic → *PanicError ~1326 120 3
Try + non-error panic + Catch hit ~1359 112 2
  • Run allocates nothing on the happy path when clauses are hoisted; inline clause construction pays slice + closure setup
  • error-typed panics skip redundant stack capture (callers() runs only for non-error panics wrapped in *PanicError)
  • On Go 1.26, Run panic recovery incurs 24 B (1 alloc) inside runtime.recovery for multi-defer unwinding
  • Fine for application-level flows; use Run over Try in hot loops

Compatibility

  • Requires Go 1.27+ (generic methods; panic(nil) detection and errors.Join semantics)
  • Fully compatible with the standard library
  • Thread-safe for concurrent use; Scope keeps per-request diagnostics isolated

Migrating from v2 to v3

  1. Module path: import github.com/linkerlin/gotrycatch/v3 and github.com/linkerlin/gotrycatch/v3/errtypes. The v2 line remains available for Go 1.21–1.26.
  2. Remove explicitly typed package-level calls — the type is inferred from the handler:
// v2
tb = gotrycatch.Catch[errtypes.ValidationError](tb, handler)
tb = gotrycatch.CatchAs[errtypes.DatabaseError](tb, handler)

// v3
tb.Catch(handler)
tb.CatchAs(handler)
  1. CatchWithResult / CatchAsWithResult / CatchAnyWithResult are gone — use the methods on *TryBlockWithResult[T]:
// v2
tb = gotrycatch.CatchWithResult[int, string](tb, handler)
tb = gotrycatch.CatchAsWithResult[int, errtypes.DatabaseError](tb, handler)
tb = gotrycatch.CatchAnyWithResult[int](tb, handler)

// v3
tb.Catch(handler)
tb.CatchAs(handler)
tb.CatchAny(handler)
  1. The errors compatibility package is removed — import errtypes directly.
  2. New capabilities: Then / ThenErr / Recover / RecoverAs pipelines, Policy, Scope, ErrorAs / ValueAs. See The v3 Way.
  3. SetDebug / SetDebugOutput still work as process-wide defaults. Prefer Scope for request- or test-local control.

Behavior changes & highlights in 2.2 – 2.5 (v2 line)

  1. Cleanup isolation (2.2): A panic inside Cleanup is returned from Run (joined with an unhandled business error when both happen). Every cleanup still runs LIFO.
  2. HandlerPanic & stack (2.2 / 2.3): A panic inside a handler propagates as *HandlerPanic (Value, Original, Cleanup, Stack()). In 2.3, HandlerPanic.Error() also reports Cleanup when non-nil.
  3. NetworkError.Is & pointer targets (2.2): NetworkError.Is compares StatusCode; all builtin Is methods accept non-nil pointer targets.
  4. Run1(nil) (2.2): returns zero value and nil, same as Run(nil).
  5. MapIs & NearMissError tree scan (2.3): MapIs translates errors.Is matches into returned errors; NearMissError now scans inside %w and errors.Join chains for OnAs/MapAs without cross-package name false positives.
  6. Stdlib interoperability & faster error capture (2.4): errtypes uses a single stack walk (newBase), implements json.Marshaler (MarshalJSON = ToJSON()) and slog.LogValuer (LogValue()), adds optional .WithCause(err)/Unwrap() to NetworkError/ConfigError/AuthError, and adds Must[T]/MustMsg[T]. gotrycatch/v2/errors is marked Deprecated (use errtypes).
  7. Zero-value Is guards & Try(nil) alignment (2.5 — behavior fixes): All 7 builtin errtypes errors reject empty/zero match keys in Is (e.g., empty Operation/Table, URL, Rule, Key, or Resource never matches); Try(nil) and TryWithResult(nil) are now no-ops returning empty blocks without error, matching Run(nil) and Run1(nil).

recover() around Run sees *HandlerPanic, not the raw value the handler panicked with:

defer func() {
    hp, ok := recover().(*gotrycatch.HandlerPanic)
    if !ok {
        return
    }
    fmt.Println(hp.Value)    // "handler blew up"
    fmt.Println(hp.Original) // the panic the handler was handling
    fmt.Println(hp.Stack())  // call stack of the handler panic
}()
_ = gotrycatch.Run(func() {
    panic(errtypes.NewValidationError("email", "bad", 1))
}, gotrycatch.On(func(errtypes.ValidationError) {
    panic("handler blew up")
}))

FAQ

Q: Why does v3 require Go 1.27?

A: Generic methods. Go 1.27 lets a method declare its own type parameters, so the error type is inferred from the handler and stays on the block:

gotrycatch.Try(func() { ... }).
    Catch(func(e errtypes.ValidationError) { ... }).
    Finally(cleanup)

Interfaces still cannot declare generic methods, so TryBlock, TryBlockWithResult[T], Policy and Scope are concrete types by design.

Q: How do I debug type matching issues?

A: Enable debug mode globally, or scope it:

gotrycatch.SetDebug(true)

// Request-local, no global state:
scope := gotrycatch.NewScope(gotrycatch.WithDebug(true))
scope.Try(func() { ... }).Catch(func(e errtypes.ConfigError) {})
// Output: [gotrycatch] Catch: type errtypes.ValidationError does not match target type errtypes.ConfigError
// Output: [gotrycatch] Catch: type errtypes.ValidationError matched, calling handler

Q: What happens to unhandled errors?

A: With Run/Run1, unhandled errors are returned as a regular error (never silently dropped). With classic Try, unhandled errors are re-thrown after Finally executes.

Examples

See the cmd/demo directory for more:

  • Basic usage
  • Handling multiple error types
  • Structured error output (ToMap/ToJSON)
  • TryWithResult patterns
  • Error chains (Unwrap/Is)
  • A real-world multi-catch scenario
  • Run clause-based API (On/OnAs/OnIs/MapAs/MapIs/Cleanup)
  • v3 generic methods, Then/Recover pipelines, Policy and Scope

Run examples

# Demo (11 detailed demos)
go run ./cmd/demo

# Run tests
go test -v ./...

# Run with coverage
go test -cover ./...

# Run with race detector
go test -race ./...

License

MIT License


GoTryCatch

一个基于 Go 泛型的类型安全异常处理库,为 Go 带来类似 try-catch 的异常处理能力。

特性

  • 🎯 类型安全: 使用 Go 泛型确保异常处理的类型安全
  • 🔗 完整链式调用: Go 1.27 泛型方法让 Catch / CatchAs 留在块上,整条管道自上而下一路点到底,无需写类型实参
  • 🏷️ 七种异常类型: 内置常用异常类型(验证、数据库、网络、业务逻辑、认证、配置、限流)
  • 📊 结构化输出: 所有错误支持 ToMap() 和 ToJSON(),便于 Agent 解析和日志记录
  • 🔍 丰富上下文: 错误自动包含文件名、行号、函数名、时间戳和调用堆栈
  • 🔄 Cleanup: Run 在同一次调用里注册 Cleanup。经典 Finally 只有被调用才执行,Catch handler 若先 panic 则轮不到后面的 Finally
  • 🎁 结果管道: TryWithResult 支持 Then / ThenErr / Recover / RecoverAs,以及原有的 OnSuccess/OnError/OrElse
  • 🧰 可复用策略: Policy 把一组错误映射规则封装一次,任意入口复用
  • 🔬 请求级调试: Scope 把调试开关与清理逻辑收在请求/测试作用域内,不污染全局
  • 🐛 调试模式: 可选的调试日志,帮助排查类型匹配问题
  • ⚡ 断言辅助: Assert 和 AssertNoError 简化条件检查
  • 📦 零依赖: 纯 Go 实现,无外部依赖
  • 🚀 高性能: 基于 Go 的 panic/recover 机制,性能开销极小

重要说明

需要 Go 1.27+。 v3 的 tb.Catch(handler) 依赖 Go 1.27 泛型方法;v2 的函数式写法(Catch[T](tb, handler)、CatchWithResult、CatchAsWithResult)在 v3 中已移除。迁移见从 v2 迁移到 v3。

语义边界

在生产环境依赖本库之前,请先阅读以下边界:

  1. Catch handler 内部发生 panic 会立即向上传播,并跳过之后才调用的 Finally。调用链是普通函数调用而非 defer 块。请保证 handler 本身不 panic,或为其单独包一层 Try。
  2. Finally 内部的 panic 会覆盖原始错误——与 Go 原生 defer 语义一致。若 Finally 中的清理可能失败,请自行 recover 保护。
  3. Try 不捕获 fn 内启动的 goroutine 的 panic。recover 只在同一 goroutine 内有效;子 goroutine 的未处理 panic 仍会崩溃整个进程。
  4. Catch 与 On 是精确类型断言,不是 errors.As。panic(&err) 匹配不了 Catch(func(Err)) 或 On(func(Err))。CatchAs / OnAs / MapAs 能穿透 fmt.Errorf("...: %w", err),但 E 和 *E 仍是两个目标。errtypes 的构造函数返回值类型,子句请写值类型。若一个子句只差指针深度且最终没人处理(OnAs/MapAs 会穿透 %w 与 errors.Join 树检查),Run 返回 *NearMissError(Unwrap 是原来的错误)。Any 会盖住这条提示;打开 SetDebug 可以在日志里看到。
  5. Cleanup 都会执行,顺序是 LIFO;其中一个 panic,其余仍会执行。清理 panic 成为 Run 的返回错误;若同时还有未处理的业务错误,两者用 errors.Join 合在一起。handler 内的 panic 在清理之后继续向外传播,类型是 *HandlerPanic:Value 是 handler 抛出的值,Original 是它接到的那次 panic,Stack() 保留 handler panic 现场堆栈,Unwrap 能走到原来的 error(清理也失败时一并带上)。子 goroutine 的 panic 捕获不到。
  6. Finally 重抛的是原来的值,新的栈从 Finally 开始。要看捕获现场的栈,先调用 Err 再调用 Finally。OrElse / OrElseGet 会用默认值换掉任何 panic,不论是否已经处理。需要看见错误时用 Result 或 Run1。

安装

go get github.com/linkerlin/gotrycatch/v3

v3 推荐用法:泛型方法

Go 1.27 允许方法声明自己的类型参数,链式调用不再断裂。无需显式类型实参,无需反复 tb = 重赋值,输入 tb. 后 IDE 也能补全 Catch:

gotrycatch.Try(func() { doWork() }).
    CatchAs(func(e errtypes.ValidationError) { /* errors.As,穿透 %w */ }).
    Catch(func(s string) { /* 精确类型 */ }).
    CatchAny(func(v interface{}) { /* 兜底 */ }).
    Finally(func() { /* 清理 */ })

TryWithResult 新增值变换与恢复:

displayName, err := gotrycatch.TryWithResult(func() []byte { return mustRead(path) }).
    Then(func(raw []byte) User { return mustParseUser(raw) }).
    Then(func(u User) string { return u.DisplayName }).
    RecoverAs(func(e errtypes.ConfigError) string { return "guest" }).
    Result()
  • Then / ThenErr:把 T 变换成 U;未处理的 panic 会让后续链路短路。函数内部 panic 会成为新块的错误。
  • Recover / RecoverAs:把未处理的 panic 变成替代值 T;与 Catch 不同,结果不会被丢掉。Recover 精确匹配,RecoverAs 穿透包装链。
  • ErrorAs[E]() (E, bool):一行按 errors.As 语义取出类型化错误,两种块都支持。
  • ValueAs[T]() (T, bool):精确取出非 error 的 panic 值。

可复用策略

var apiPolicy = gotrycatch.NewPolicy().
    MapAs(func(e errtypes.ValidationError) error { return httpErr(400, e) }).
    MapAs(func(e errtypes.AuthError) error { return httpErr(401, e) }).
    MapAs(func(e errtypes.RateLimitError) error { return httpErr(429, e) })

user, err := apiPolicy.Run1(func() User { return loadUser(id) })

Policy 构建后只读,可跨 handler 共享,不必每个请求重建子句切片。

请求级诊断

scope := gotrycatch.NewScope(
    gotrycatch.WithDebug(true),
    gotrycatch.WithLogger(reqLogger), // *slog.Logger
    gotrycatch.WithCleanup(func() { releaseRequestResources() }),
)

res, err := scope.Run1(func() Order {
    cfg := scope.Must(loadConfig())
    return buildOrder(cfg)
})

Scope 不会改动进程级 SetDebug,并行测试与按请求开启的诊断互不干扰。

单语句入口:Run

Run 仍然是“一次调用必然执行”的防呆入口,不可能忘记清理,结果直接进入 Go 惯用的 error 流:

import (
    "fmt"

    "github.com/linkerlin/gotrycatch/v3"
    "github.com/linkerlin/gotrycatch/v3/errtypes"
)

func loadUser(id string) error {
    err := gotrycatch.Run(func() { queryUser(id) },
        // errors.As 语义:可穿透 fmt.Errorf("%w", ...) 包装
        gotrycatch.OnAs(func(e errtypes.DatabaseError) {
            retry(id)
        }),
        gotrycatch.On(func(e errtypes.RateLimitError) {
            wait(e.RetryAfter)
        }),
        // 总是执行、LIFO,handler panic 也不会跳过
        gotrycatch.Cleanup(func() { conn.Close() }),
    )
    if err != nil {
        return fmt.Errorf("load user %s: %w", id, err)
    }
    return nil
}

为什么难以误用:

  • 未处理的 panic 以 error 返回——在结构上不可能静默吞错。error 型 panic 原样直通(errors.Is/As 全链路可用);其他值包装为 *PanicError。
  • Cleanup 总是执行——内联声明,LIFO。清理函数自己的 panic 回到返回的 error 上,不会把未处理的业务错误冲掉。
  • 子句是有序的值——无需记忆方法/函数混链规则。
  • Run1 支持返回值:v, err := gotrycatch.Run1(fn, clauses...)。

哨兵错误用 OnIs(或用 MapIs 翻译),它们不会把别的错误一起吃掉。要把命中的 panic 翻译成你要返回的 error,用 MapAs 或 MapIs:

err := gotrycatch.Run(func() { open(path) },
    gotrycatch.OnIs(os.ErrNotExist, func(error) { useDefault() }),
    gotrycatch.MapIs(os.ErrPermission, func(e error) error {
        return fmt.Errorf("permission denied: %w", e)
    }),
    gotrycatch.MapAs(func(e errtypes.DatabaseError) error {
        return fmt.Errorf("query: %w", e)
    }),
)

OnAs(func(e error)) 和 On(func(e error)) 会匹配每一个 error,并视为已处理。只想消费一个哨兵时,把 OnIs/MapIs 放在这种宽子句前面。

快速开始(链式 API)

Run 仍是单语句入口;链式 API 继续完整支持:

基本用法

package main

import (
    "fmt"

    "github.com/linkerlin/gotrycatch/v3"
    "github.com/linkerlin/gotrycatch/v3/errtypes"
)

func main() {
    gotrycatch.Try(func() {
        // 可能会 panic 的代码
        gotrycatch.Throw(errtypes.NewValidationError("email", "格式无效", 1001))
    }).Catch(func(err errtypes.ValidationError) {
        fmt.Printf("验证错误: %s (字段: %s, 代码: %d)\n", err.Message, err.Field, err.Code)
    }).Finally(func() {
        fmt.Println("清理工作完成")
    })
}

TryWithResult - 带返回值的函数

// 执行带返回值的函数
tb := gotrycatch.TryWithResult(func() int {
    return computeValue()
})

// 成功回调
tb.OnSuccess(func(result int) {
    fmt.Println("结果:", result)
})

// 错误回调
tb.OnError(func(err interface{}) {
    fmt.Println("错误:", err)
})

// 获取结果,有错误时返回默认值
result := tb.OrElse(0)

// 或者延迟计算默认值
result := tb.OrElseGet(func() int { return computeDefault() })

需要变换或恢复时,用 v3 管道方法:

result, err := gotrycatch.TryWithResult(func() int { return computeValue() }).
    Then(func(n int) string { return strconv.Itoa(n) }).
    Recover(func(err errtypes.ConfigError) string { return "default" }).
    Result()

多种异常类型处理

gotrycatch.Try(func() {
    processUserData()
}).Catch(func(err errtypes.ValidationError) {
    fmt.Printf("验证失败: %s\n", err.Message)
}).Catch(func(err errtypes.DatabaseError) {
    fmt.Printf("数据库错误: %s on table %s\n", err.Operation, err.Table)
}).Catch(func(err errtypes.NetworkError) {
    if err.Timeout {
        fmt.Printf("网络超时: %s\n", err.URL)
    } else {
        fmt.Printf("网络错误 %d: %s\n", err.StatusCode, err.URL)
    }
}).CatchAny(func(err interface{}) {
    fmt.Printf("未知错误: %v\n", err)
}).Finally(func() {
    fmt.Println("处理完成")
})

状态查询和调试

tb := gotrycatch.Try(func() {
    riskyOperation()
})

// 查询状态
if tb.HasError() {
    fmt.Printf("错误类型: %s\n", tb.GetErrorType())
    fmt.Printf("错误值: %v\n", tb.GetError())
}

if !tb.IsHandled() {
    // 根据错误类型决定处理方式
    switch tb.GetErrorType() {
    case "errtypes.ValidationError":
        // 处理验证错误
    default:
        tb = tb.CatchAny(func(err interface{}) {
            logUnknownError(err)
        })
    }
}

// 开启调试模式追踪类型匹配
gotrycatch.SetDebug(true)

结构化错误输出(Agent 友好)

tb := gotrycatch.Try(func() { processOrder() })
tb.Catch(func(err errtypes.BusinessLogicError) {
    // JSON 输出便于日志和 Agent 解析
    jsonData, _ := err.ToJSON()
    log.Printf("ERROR: %s", string(jsonData))
    // 输出: {"type":"BusinessLogicError","rule":"inventory_check","details":"库存不足","file":"main.go","line":42,"function":"processOrder","timestamp":"2024-01-15T10:30:00Z","stack":[...]}
})

// 或者一行按 errors.As 语义取出类型化错误
if ve, ok := tb.ErrorAs[errtypes.ValidationError](); ok {
    fmt.Println(ve.Field, ve.Code)
}

断言辅助函数

// 条件断言,false 时抛出错误
gotrycatch.Assert(value != "", errtypes.NewValidationError("value", "不能为空", 1001))

// 错误断言,有错误时包装并抛出
gotrycatch.AssertNoError(err, "数据库操作失败")

内置异常类型

所有错误类型都包含:File、Line、Function、Timestamp、Stack

类型 专有字段 构造函数 用途
ValidationError Field, Message, Code NewValidationError(field, message, code) 数据验证错误
DatabaseError Operation, Table, Cause NewDatabaseError(operation, table, cause) 数据库操作错误
NetworkError URL, StatusCode, Timeout, Cause NewNetworkError(url, code) / .WithCause(err) HTTP 错误
NetworkError URL, Timeout, Cause NewNetworkTimeoutError(url) / .WithCause(err) 网络超时
BusinessLogicError Rule, Details NewBusinessLogicError(rule, details) 业务规则违规
ConfigError Key, Value, Reason, Cause NewConfigError(key, value, reason) / .WithCause(err) 配置错误(敏感 Value 请先脱敏)
AuthError Operation, User, Reason, Cause NewAuthError(operation, user, reason) / .WithCause(err) 认证授权错误
RateLimitError Resource, Limit, Current, RetryAfter NewRateLimitError(resource, limit, current, retryAfter) 限流错误

错误方法

var err errtypes.ValidationError

err.Error()       // string - 完整错误描述(含位置信息)
err.ToMap()       // map[string]interface{} - 结构化数据
err.ToJSON()      // ([]byte, error) - JSON 输出
err.MarshalJSON() // ([]byte, error) - json.Marshaler,与 ToJSON() 输出一致
err.LogValue()    // slog.Value - slog.LogValuer 零依赖结构化输出(Go 1.21+ 标准库)
err.Unwrap()      // error - 底层错误(DatabaseError 与 WithCause 支持)
err.Is(target)    // bool - 错误匹配

API 文档

核心函数

函数/方法 签名 说明
Run func Run(fn func(), clauses ...Clause) error v2 惯用法子句式执行;未处理 panic 以 error 返回
Run1 func Run1[T any](fn func() T, clauses ...Clause) (T, error) v2 带返回值的 Run
On[E] func On[E any](handler func(E)) Clause v2 子句:精确类型匹配(Catch 语义)
OnAs[E] func OnAs[E error](handler func(E)) Clause v2 子句:errors.As 匹配,穿透 %w 包装。E 与 *E 是不同目标
OnIs func OnIs(target error, handler func(error)) Clause v2.2 子句:errors.Is 匹配;其他错误继续往后
Map[E] func Map[E any](handler func(E) error) Clause v2.2 精确匹配;handler 返回的非 nil error 成为 Run 的结果
MapAs[E] func MapAs[E error](handler func(E) error) Clause v2.2 errors.As 匹配;handler 返回的非 nil error 成为 Run 的结果
MapIs func MapIs(target error, handler func(error) error) Clause v2.3 errors.Is 匹配;handler 返回的非 nil error 成为 Run 的结果
Any func Any(handler func(interface{})) Clause v2 子句:任意 panic 兜底
Cleanup func Cleanup(fn func()) Clause v2.2 总是执行、LIFO;这里的 panic 变成返回的 error
Try func Try(fn func()) *TryBlock 执行函数并捕获 panic
(*TryBlock).Catch[E] func (tb *TryBlock) Catch[E any](handler func(E)) *TryBlock v3 处理精确类型 E 的异常;可链式调用,类型自动推导
(*TryBlock).CatchAs[E] func (tb *TryBlock) CatchAs[E error](handler func(E)) *TryBlock v3 errors.As 匹配。E 与 *E 是不同目标
(*TryBlock).CatchAny func (tb *TryBlock) CatchAny(handler func(interface{})) *TryBlock 处理任何未处理的异常
(*TryBlock).ErrorAs[E] func (tb *TryBlock) ErrorAs[E error]() (E, bool) v3 按 errors.As 语义一行提取类型化错误
(*TryBlock).ValueAs[T] func (tb *TryBlock) ValueAs[T any]() (T, bool) v3 精确提取 panic 值
Finally func (tb *TryBlock) Finally(fn func()) 执行清理代码

包装错误类型(v2)

类型 关键字段 / 方法 说明
PanicError Value、Unwrap()、Stack() []string 在 Run/Err() 中包装非 error 型 panic;惰性抓栈
HandlerPanic Value、Original、Cleanup、Unwrap()、Stack() []string handler 内发生二次 panic 时向外传播;清理仍全部执行
NearMissError Err、Hint、Unwrap() 未处理 panic 与子句同类型仅差指针深度时自动附加提示

TryBlock 状态查询

方法 返回类型 说明
HasError() bool 是否捕获了错误
GetError() interface{} 获取错误值
Err() error v2 panic 桥接为 error(支持 errors.Is/As;非 error panic 包装为 *PanicError)
GetErrorType() string 获取错误类型名(如 "errtypes.ValidationError")
CanonicalErrorType() string v2 去指针短类型名(如 "ValidationError")
IsHandled() bool 错误是否已被处理
String() string 友好的字符串表示

TryWithResult

函数/方法 签名 说明
TryWithResult func TryWithResult[T any](fn func() T) *TryBlockWithResult[T] 执行带返回值的函数
Catch[E] func (tb *TryBlockWithResult[T]) Catch[E any](handler func(E)) *TryBlockWithResult[T] v3 类型捕获;E 从 handler 推导
CatchAs[E] func (tb *TryBlockWithResult[T]) CatchAs[E error](handler func(E)) *TryBlockWithResult[T] v3 errors.As 捕获
CatchAny func (tb *TryBlockWithResult[T]) CatchAny(handler func(interface{})) *TryBlockWithResult[T] 任意捕获
Then[U] func (tb *TryBlockWithResult[T]) Then[U any](fn func(T) U) *TryBlockWithResult[U] v3 变换结果;未处理 panic 短路
ThenErr[U] func (tb *TryBlockWithResult[T]) ThenErr[U any](fn func(T) (U, error)) *TryBlockWithResult[U] v3 可失败的结果变换
Recover[E] func (tb *TryBlockWithResult[T]) Recover[E any](fn func(E) T) *TryBlockWithResult[T] v3 从精确类型 panic 产生替代值
RecoverAs[E] func (tb *TryBlockWithResult[T]) RecoverAs[E error](fn func(E) T) *TryBlockWithResult[T] v3 穿透 %w 的恢复
ErrorAs[E] func (tb *TryBlockWithResult[T]) ErrorAs[E error]() (E, bool) v3 按 errors.As 语义提取类型化错误
GetResult() T 获取结果值
OnSuccess func (tb *TryBlockWithResult[T]) OnSuccess(fn func(T)) *TryBlockWithResult[T] 成功时回调
OnError func (tb *TryBlockWithResult[T]) OnError(fn func(interface{})) *TryBlockWithResult[T] 错误时回调
OrElse func (tb *TryBlockWithResult[T]) OrElse(defaultValue T) T 任何 panic 都换成默认值(含未处理的);错误被丢弃
OrElseGet func (tb *TryBlockWithResult[T]) OrElseGet(supplier func() T) T 任何 panic 都延迟计算默认值;错误被丢弃
Result func (tb *TryBlockWithResult[T]) Result() (T, error) 返回值和错误;未处理 panic 经 Err 返回

Policy 与 Scope(v3)

函数/方法 签名 说明
NewPolicy func NewPolicy(clauses ...Clause) *Policy 构建可复用子句集
(*Policy).On/OnAs/OnIs 泛型方法,可链式 规则构建器
(*Policy).Map/MapAs/MapIs/Any/Cleanup 可链式 与包级子句构造器同名同义
(*Policy).Run func (p *Policy) Run(fn func()) error 在策略下执行
(*Policy).Run1[T] func (p *Policy) Run1[T any](fn func() T) (T, error) 执行并推导返回类型
NewScope func NewScope(opts ...ScopeOption) *Scope 请求/测试局部诊断
WithDebug func WithDebug(enabled bool) ScopeOption 只影响该 Scope 的调试开关
WithLogger func WithLogger(logger *slog.Logger) ScopeOption 诊断日志输出
WithCleanup func WithCleanup(fn func()) ScopeOption 每次 scope Run/Run1 后执行
(*Scope).Try/TryWithResult/Run/Run1/Must 泛型方法 核心 API 的作用域版本

调试与断言

函数 签名 说明
SetDebug func SetDebug(enabled bool) 开启/关闭调试日志(整个进程)
SetDebugOutput func SetDebugOutput(w io.Writer) 调试输出;nil 恢复 stderr(整个进程)
IsDebug func IsDebug() bool 查询调试模式状态
Throw func Throw(err interface{}) 抛出异常(panic)
Assert func Assert(condition bool, err interface{}) 条件断言,false 时抛出
AssertNoError func AssertNoError(err error, msg string) 错误断言,有错误时抛出
Must func Must[T any](v T, err error) T v2.4 err == nil 返回 v,否则直接 Throw(err)
MustMsg func MustMsg[T any](v T, err error, msg string) T v2.4 err == nil 返回 v,否则用 msg 包装(%w)并抛出

最佳实践

  1. 按特定性排序 Catch 块: 将最具体的异常类型放在前面,通用类型放在后面
  2. 新代码优先用 Run 和 Cleanup: 经典 Finally 只有被调用才执行
  3. 使用预定义异常类型: 优先使用库提供的异常类型,而不是原始字符串或数字
  4. 使用 CatchAny 作为兜底: 优雅地处理未预期的错误类型
  5. 调试时开启调试模式: 当类型匹配不符合预期时,使用 SetDebug(true) 排查
  6. 日志使用 ToJSON: 结构化输出更易于解析和分析

性能考虑

使用 go test -run '^$' -bench . -benchmem -benchtime=200ms ./... 实测(go1.26.5 windows/amd64,i9-13900HX,仅供参考):

场景 ns/op B/op allocs/op
error 返回值(Go 惯用基线) ~0.16 0 0
原生 recover,无 panic ~2.2 0 0
Run1,无 panic(预构造子句) ~22 0 0
Run,无 panic(预构造子句) ~24 0 0
Run,无 panic(内联子句) ~426 96 5
Try,无 panic ~30 48 1
TryWithResult + OrElse,无 panic ~61 64 1
原生 recover,panic 路径(error) ~177 0 0
Run + panic + On 命中(string) ~402 24 1
Run + error 型未处理 panic ~483 24 1
Try + error 型 panic + Catch 命中 ~543 48 1
Run + 非 error 未处理 panic → *PanicError ~1326 120 3
Try + 非 error panic + Catch 命中 ~1359 112 2
  • 预构造子句时 Run 快乐路径零分配;内联构造子句需支付切片与闭包构建开销
  • error 型 panic 跳过冗余抓栈(仅非 error panic 包装 *PanicError 时调用 callers())
  • Go 1.26 下 Run 的 panic 恢复路径由 runtime.recovery 产生 24 B(1 alloc)多 defer 展开开销
  • 适合应用级流程;热循环优先用 Run 而非 Try

兼容性

  • 需要 Go 1.27+(泛型方法;panic(nil) 检测与 errors.Join 语义)
  • 与标准库完全兼容
  • 并发安全;Scope 保证请求级诊断互不干扰

从 v2 迁移到 v3

  1. 模块路径:导入 github.com/linkerlin/gotrycatch/v3 与 github.com/linkerlin/gotrycatch/v3/errtypes。Go 1.21–1.26 用户继续使用 v2。
  2. 删除显式类型实参——类型从 handler 推导:
// v2
tb = gotrycatch.Catch[errtypes.ValidationError](tb, handler)
tb = gotrycatch.CatchAs[errtypes.DatabaseError](tb, handler)

// v3
tb.Catch(handler)
tb.CatchAs(handler)
  1. CatchWithResult / CatchAsWithResult / CatchAnyWithResult 已移除——改用 *TryBlockWithResult[T] 上的方法:
// v2
tb = gotrycatch.CatchWithResult[int, string](tb, handler)
tb = gotrycatch.CatchAsWithResult[int, errtypes.DatabaseError](tb, handler)
tb = gotrycatch.CatchAnyWithResult[int](tb, handler)

// v3
tb.Catch(handler)
tb.CatchAs(handler)
tb.CatchAny(handler)
  1. errors 兼容包已删除——直接导入 errtypes。
  2. 新增能力:Then / ThenErr / Recover / RecoverAs 管道、Policy、Scope、ErrorAs / ValueAs。见 v3 推荐用法。
  3. SetDebug / SetDebugOutput 仍是进程级默认开关;请求或测试作用域优先用 Scope。

2.2 – 2.5 的行为变化与特性增强(v2 系列)

  1. Cleanup 隔离(2.2):Cleanup 里的 panic 从 Run 返回(若同时有未处理的业务错误,用 errors.Join 合在一起)。其余 Cleanup 仍按 LIFO 执行。
  2. HandlerPanic 与堆栈(2.2 / 2.3):handler 里的 panic 以 *HandlerPanic 向外传播(Value、Original、Cleanup、Stack())。自 2.3 起,若同时存在清理失败,HandlerPanic.Error() 也会一并输出清理错误。
  3. NetworkError.Is 与指针目标(2.2):NetworkError.Is 同时比较 StatusCode;内置类型的 Is 也接受非 nil 指针目标。
  4. Run1(nil)(2.2):返回零值和 nil,与 Run(nil) 相同。
  5. MapIs 与 NearMissError 树扫描(2.3):MapIs 支持按 errors.Is 将哨兵错误翻译为返回值;OnAs/MapAs 的 NearMissError 提示可穿透 %w 与 errors.Join 树检查,且不再跨包同名误报。
  6. 标准库互操作与单次抓栈优化(2.4):errtypes 合并为单次调用栈抓取(newBase),实现 json.Marshaler(MarshalJSON 与 ToJSON() 一致)与 slog.LogValuer(LogValue()),为 NetworkError/ConfigError/AuthError 增设可选 .WithCause(err)/Unwrap(),并新增泛型桥接 Must[T]/MustMsg[T];gotrycatch/v2/errors 标注 Deprecated。
  7. 零值 Is 护栏与 Try(nil) 对齐(2.5 — 行为修正):全部 7 种 errtypes 内置错误的 Is 均拒绝空/零值匹配键(空 Operation/Table、URL、Rule、Key、Resource 与零 Code 互不匹配);Try(nil) 与 TryWithResult(nil) 改为返回无错误的空块,与 Run(nil) / Run1(nil) 一致。

包在 Run 外面的 recover() 得到 *HandlerPanic,不再是 handler 抛出的原值:

defer func() {
    hp, ok := recover().(*gotrycatch.HandlerPanic)
    if !ok {
        return
    }
    fmt.Println(hp.Value)    // "handler blew up"
    fmt.Println(hp.Original) // handler 正在处理的那次 panic
    fmt.Println(hp.Stack())  // handler panic 的调用堆栈
}()
_ = gotrycatch.Run(func() {
    panic(errtypes.NewValidationError("email", "bad", 1))
}, gotrycatch.On(func(errtypes.ValidationError) {
    panic("handler blew up")
}))

常见问题 (FAQ)

Q: 为什么 v3 需要 Go 1.27?

A: 因为泛型方法。Go 1.27 允许方法声明自己的类型参数,错误类型从 handler 推导,并留在块上:

gotrycatch.Try(func() { ... }).
    Catch(func(e errtypes.ValidationError) { ... }).
    Finally(cleanup)

接口仍不能声明泛型方法,所以 TryBlock、TryBlockWithResult[T]、Policy、Scope 都设计为具象类型。

Q: 如何调试类型匹配问题?

A: 可以全局开启,也可以按请求开启:

gotrycatch.SetDebug(true)

// 请求级,不动全局状态:
scope := gotrycatch.NewScope(gotrycatch.WithDebug(true))
scope.Try(func() { ... }).Catch(func(e errtypes.ConfigError) {})
// 输出: [gotrycatch] Catch: type errtypes.ValidationError does not match target type errtypes.ConfigError
// 输出: [gotrycatch] Catch: type errtypes.ValidationError matched, calling handler

Q: 未处理的错误会怎样?

A: 使用 Run/Run1 时,未处理的错误会直接作为 error 返回(不可能静默吞错)。使用经典 Try 时,未处理的错误会在 Finally 执行后重新抛出。

示例

查看 cmd/demo 目录获取详细示例,包括:

  • 基本用法演示
  • 多种异常类型处理
  • 结构化输出(ToMap/ToJSON)
  • TryWithResult 模式
  • 错误链(Unwrap/Is)
  • 真实场景多 Catch 示例
  • Run 子句式 API(On/OnAs/OnIs/MapAs/MapIs/Cleanup)
  • v3 泛型方法、Then/Recover 管道、Policy 与 Scope

运行示例

# 演示程序(11个详细Demo)
go run ./cmd/demo

# 运行测试
go test -v ./...

# 查看覆盖率
go test -cover ./...

# 竞态检测
go test -race ./...

许可证

MIT License

About

A lib for using trycatch in Go!

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages