A type-safe exception handling library based on Go generics that brings try-catch-like capabilities to Go.
- 🎯 Type-safe: Uses Go generics to ensure type-safe exception handling
- 🔗 Full chaining: Go 1.27 generic methods keep
Catch/CatchAson 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()andToJSON()for easy parsing by agents/logs - 🔍 Rich context: Errors include file, line, function, timestamp, and stack trace
- 🔄 Cleanup:
RunregistersCleanupwith the call. ClassicFinallyruns only when you call it, and a panicking Catch handler never reaches a laterFinally - 🎁 Result pipelines:
TryWithResultsupportsThen/ThenErr/Recover/RecoverAsin addition toOnSuccess/OnError/OrElse - 🧰 Reusable policies:
Policypackages a clause set once and runs it from any entry point - 🔬 Request-scoped debugging:
Scopekeeps 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
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.
Read these before relying on this library in production:
- A panic inside a Catch handler propagates immediately and skips any later
Finallycall. The chain is plain function calls, not a deferred block. Keep handler bodies non-panicking, or wrap them in their ownTry. - A panic inside
Finallyreplaces the original error — same as Go's nativedefer. IfFinallymust run fallible cleanup, guard it with its own recover. Trydoes not catch panics from goroutines started insidefn.recoveronly works within the same goroutine; an unhandled panic in a child goroutine still crashes the process.CatchandOnare exact type assertions, noterrors.As.panic(&err)does not matchCatch(func(Err))orOn(func(Err)).CatchAs/OnAs/MapAspenetratefmt.Errorf("...: %w", err)wrapping, andEand*Eare different targets.errtypesconstructors return values, so write the value type in the clause. If nothing handles a clause that differs only by pointer depth (including inside%worerrors.Joinchains forOnAs/MapAs),Runreturns*NearMissError(itsUnwrapis the original error).Anyswallows that hint; turn onSetDebugto log it.- 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:Valueis what the handler panicked with,Originalis the panic it received,Stack()holds the handler panic trace, andUnwrapreaches the original error (and the cleanup error, when there is one). Panics in a child goroutine are never captured. Finallyre-panics the original value, so the stack of that panic starts atFinally. CallErrbeforeFinallyto read the stack captured at the original panic site.OrElse/OrElseGetreplace any panic with the default, handled or not. UseResultorRun1when the error must stay visible.
go get github.com/linkerlin/gotrycatch/v3Go 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: transformTintoU; 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 replacementT; unlikeCatch, the value is not thrown away.Recoveris exact,RecoverAsunwraps.ErrorAs[E]() (E, bool): one-line extraction witherrors.Assemantics, on both block types.ValueAs[T]() (T, bool): exact extraction of a non-error panic value.
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.
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.
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 (soerrors.Is/Aswork 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.
Run1covers 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.
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")
})
}// 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()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")
})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)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)
}// 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")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 |
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| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
- Order Catch blocks by specificity: Most specific types first, generic types later
- Prefer
RunandCleanupfor new code: ClassicFinallyruns only when called - Use predefined error types: Prefer structured errors over raw strings/numbers
- Use CatchAny as fallback: Handle unexpected error types gracefully
- Enable debug mode for troubleshooting: Use
SetDebug(true)when type matching doesn't work as expected - Use ToJSON for logging: Structured output is easier to parse and analyze
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 |
Runallocates nothing on the happy path when clauses are hoisted; inline clause construction pays slice + closure setuperror-typed panics skip redundant stack capture (callers()runs only for non-error panics wrapped in*PanicError)- On Go 1.26,
Runpanic recovery incurs 24 B (1 alloc) insideruntime.recoveryfor multi-defer unwinding - Fine for application-level flows; use
RunoverTryin hot loops
- Requires Go 1.27+ (generic methods;
panic(nil)detection anderrors.Joinsemantics) - Fully compatible with the standard library
- Thread-safe for concurrent use;
Scopekeeps per-request diagnostics isolated
- Module path: import
github.com/linkerlin/gotrycatch/v3andgithub.com/linkerlin/gotrycatch/v3/errtypes. The v2 line remains available for Go 1.21–1.26. - 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)CatchWithResult/CatchAsWithResult/CatchAnyWithResultare 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)- The
errorscompatibility package is removed — importerrtypesdirectly. - New capabilities:
Then/ThenErr/Recover/RecoverAspipelines,Policy,Scope,ErrorAs/ValueAs. See The v3 Way. SetDebug/SetDebugOutputstill work as process-wide defaults. PreferScopefor request- or test-local control.
Cleanupisolation (2.2): A panic insideCleanupis returned fromRun(joined with an unhandled business error when both happen). Every cleanup still runs LIFO.HandlerPanic& stack (2.2 / 2.3): A panic inside a handler propagates as*HandlerPanic(Value,Original,Cleanup,Stack()). In 2.3,HandlerPanic.Error()also reportsCleanupwhen non-nil.NetworkError.Is& pointer targets (2.2):NetworkError.IscomparesStatusCode; all builtinIsmethods accept non-nil pointer targets.Run1(nil)(2.2): returns zero value and nil, same asRun(nil).MapIs&NearMissErrortree scan (2.3):MapIstranslateserrors.Ismatches into returned errors;NearMissErrornow scans inside%wanderrors.Joinchains forOnAs/MapAswithout cross-package name false positives.- Stdlib interoperability & faster error capture (2.4):
errtypesuses a single stack walk (newBase), implementsjson.Marshaler(MarshalJSON=ToJSON()) andslog.LogValuer(LogValue()), adds optional.WithCause(err)/Unwrap()toNetworkError/ConfigError/AuthError, and addsMust[T]/MustMsg[T].gotrycatch/v2/errorsis markedDeprecated(useerrtypes). - Zero-value
Isguards &Try(nil)alignment (2.5 — behavior fixes): All 7 builtinerrtypeserrors reject empty/zero match keys inIs(e.g., emptyOperation/Table,URL,Rule,Key, orResourcenever matches);Try(nil)andTryWithResult(nil)are now no-ops returning empty blocks without error, matchingRun(nil)andRun1(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")
}))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.
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 handlerA: 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.
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/Recoverpipelines,PolicyandScope
# 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 ./...MIT License
一个基于 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。
在生产环境依赖本库之前,请先阅读以下边界:
- Catch handler 内部发生 panic 会立即向上传播,并跳过之后才调用的
Finally。调用链是普通函数调用而非 defer 块。请保证 handler 本身不 panic,或为其单独包一层Try。 Finally内部的 panic 会覆盖原始错误——与 Go 原生defer语义一致。若Finally中的清理可能失败,请自行 recover 保护。Try不捕获fn内启动的 goroutine 的 panic。recover只在同一 goroutine 内有效;子 goroutine 的未处理 panic 仍会崩溃整个进程。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可以在日志里看到。Cleanup都会执行,顺序是 LIFO;其中一个 panic,其余仍会执行。清理 panic 成为Run的返回错误;若同时还有未处理的业务错误,两者用errors.Join合在一起。handler 内的 panic 在清理之后继续向外传播,类型是*HandlerPanic:Value是 handler 抛出的值,Original是它接到的那次 panic,Stack()保留 handler panic 现场堆栈,Unwrap能走到原来的 error(清理也失败时一并带上)。子 goroutine 的 panic 捕获不到。Finally重抛的是原来的值,新的栈从Finally开始。要看捕获现场的栈,先调用Err再调用Finally。OrElse/OrElseGet会用默认值换掉任何 panic,不论是否已经处理。需要看见错误时用Result或Run1。
go get github.com/linkerlin/gotrycatch/v3Go 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 仍然是“一次调用必然执行”的防呆入口,不可能忘记清理,结果直接进入 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 放在这种宽子句前面。
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("清理工作完成")
})
}// 执行带返回值的函数
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)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 - 错误匹配| 函数/方法 | 签名 | 说明 |
|---|---|---|
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()) |
执行清理代码 |
| 类型 | 关键字段 / 方法 | 说明 |
|---|---|---|
PanicError |
Value、Unwrap()、Stack() []string |
在 Run/Err() 中包装非 error 型 panic;惰性抓栈 |
HandlerPanic |
Value、Original、Cleanup、Unwrap()、Stack() []string |
handler 内发生二次 panic 时向外传播;清理仍全部执行 |
NearMissError |
Err、Hint、Unwrap() |
未处理 panic 与子句同类型仅差指针深度时自动附加提示 |
| 方法 | 返回类型 | 说明 |
|---|---|---|
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 |
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 返回 |
| 函数/方法 | 签名 | 说明 |
|---|---|---|
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)并抛出 |
- 按特定性排序 Catch 块: 将最具体的异常类型放在前面,通用类型放在后面
- 新代码优先用
Run和Cleanup: 经典Finally只有被调用才执行 - 使用预定义异常类型: 优先使用库提供的异常类型,而不是原始字符串或数字
- 使用 CatchAny 作为兜底: 优雅地处理未预期的错误类型
- 调试时开启调试模式: 当类型匹配不符合预期时,使用
SetDebug(true)排查 - 日志使用 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保证请求级诊断互不干扰
- 模块路径:导入
github.com/linkerlin/gotrycatch/v3与github.com/linkerlin/gotrycatch/v3/errtypes。Go 1.21–1.26 用户继续使用 v2。 - 删除显式类型实参——类型从 handler 推导:
// v2
tb = gotrycatch.Catch[errtypes.ValidationError](tb, handler)
tb = gotrycatch.CatchAs[errtypes.DatabaseError](tb, handler)
// v3
tb.Catch(handler)
tb.CatchAs(handler)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)errors兼容包已删除——直接导入errtypes。- 新增能力:
Then/ThenErr/Recover/RecoverAs管道、Policy、Scope、ErrorAs/ValueAs。见 v3 推荐用法。 SetDebug/SetDebugOutput仍是进程级默认开关;请求或测试作用域优先用Scope。
Cleanup隔离(2.2):Cleanup里的 panic 从Run返回(若同时有未处理的业务错误,用errors.Join合在一起)。其余 Cleanup 仍按 LIFO 执行。HandlerPanic与堆栈(2.2 / 2.3):handler 里的 panic 以*HandlerPanic向外传播(Value、Original、Cleanup、Stack())。自 2.3 起,若同时存在清理失败,HandlerPanic.Error()也会一并输出清理错误。NetworkError.Is与指针目标(2.2):NetworkError.Is同时比较StatusCode;内置类型的Is也接受非 nil 指针目标。Run1(nil)(2.2):返回零值和 nil,与Run(nil)相同。MapIs与NearMissError树扫描(2.3):MapIs支持按errors.Is将哨兵错误翻译为返回值;OnAs/MapAs的NearMissError提示可穿透%w与errors.Join树检查,且不再跨包同名误报。- 标准库互操作与单次抓栈优化(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。 - 零值
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")
}))A: 因为泛型方法。Go 1.27 允许方法声明自己的类型参数,错误类型从 handler 推导,并留在块上:
gotrycatch.Try(func() { ... }).
Catch(func(e errtypes.ValidationError) { ... }).
Finally(cleanup)接口仍不能声明泛型方法,所以 TryBlock、TryBlockWithResult[T]、Policy、Scope 都设计为具象类型。
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 handlerA: 使用 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