### Run log example using go run Source: https://pkg.go.dev/github.com/samber/oops/examples/log This command executes the log example file located in the examples/log directory. It demonstrates the usage of the log package. ```go go run examples/log/example.go ``` -------------------------------- ### Run Zerolog Example and Process Output with jq Source: https://pkg.go.dev/github.com/samber/oops/examples/zerolog This example demonstrates how to run a zerolog example and pipe its output to the jq command for JSON processing. It shows how to view the entire output and specifically extract the stack trace. ```bash go run examples/zerolog/example.go 2>&1 | jq go run examples/zerolog/example.go 2>&1 | jq .stack -r ``` -------------------------------- ### Run Log Logger Example in Go Source: https://pkg.go.dev/github.com/samber/oops/examples/log_tab=imports This snippet shows how to run the log logger example for the amber/oops Go module. It utilizes the 'go run' command with the specified example file path. No external dependencies are required beyond a Go installation. ```bash go run examples/log/example.go ``` -------------------------------- ### Run Logrus example and parse with jq Source: https://pkg.go.dev/github.com/samber/oops/examples/logrus_tab=imports This snippet shows how to execute an example Go program that uses Logrus for logging within the "oops" module. The output is piped to `jq` for JSON parsing, allowing for structured data inspection. It assumes the `jq` command-line JSON processor is installed. ```shell go run examples/logrus/example.go 2>&1 | jq ``` -------------------------------- ### Run Logrus Example and Process Output with jq - Go Source: https://pkg.go.dev/github.com/samber/oops/examples/logrus This Go code snippet demonstrates how to execute a Logrus example and pipe its output to the 'jq' command for JSON processing. It includes variations for general output and specifically for extracting stack trace information in raw format. ```bash go run examples/logrus/example.go 2>&1 | jq go run examples/logrus/example.go 2>&1 | jq .stacktrace -r ``` -------------------------------- ### Run Zerolog example with jq Source: https://pkg.go.dev/github.com/samber/oops/examples/zerolog_tab=imports This command runs an example Go program that uses Zerolog for logging and pipes the output to jq for JSON processing. It's useful for inspecting structured logs. ```bash go run examples/zerolog/example.go 2>\&1 | jq ``` -------------------------------- ### Run Zerolog example and extract stack trace Source: https://pkg.go.dev/github.com/samber/oops/examples/zerolog_tab=imports This command executes a Go example using Zerolog and then uses jq to specifically extract and display the 'stack' field from the JSON output in its raw format. This is helpful for debugging. ```bash go run examples/zerolog/example.go 2>\&1 | jq .stack -r ``` -------------------------------- ### Run Panic Handling Example with jq in Go Source: https://pkg.go.dev/github.com/samber/oops/examples/panic_tab=licenses Demonstrates how to run the panic handling example and process its output using `jq` for structured JSON analysis. This is useful for debugging and understanding panic traces. ```shell go run examples/panic/example.go 2>\&1 | jq ``` ```shell go run examples/panic/example.go 2>\&1 | jq .stacktrace -r ``` -------------------------------- ### Install Development Dependencies and Run Tests Source: https://pkg.go.dev/github.com/samber/oops/index Provides instructions for setting up the development environment by installing dependencies using `make tools` and running tests with `make test` or `make watch-test`. ```bash # Install some dev dependencies make tools # Run tests make test # or make watch-test ``` -------------------------------- ### Run segfault example and parse output with jq Source: https://pkg.go.dev/github.com/samber/oops/examples/segfault_tab=importedby Demonstrates how to run the segfault example and process its output using jq. This is useful for inspecting structured error messages or stack traces. ```bash go run examples/segfault/example.go 2>\&1 | jq go run examples/segfault/example.go 2>\&1 | jq .stacktrace -r ``` -------------------------------- ### Run Zerolog Example and Process Output with jq Source: https://pkg.go.dev/github.com/samber/oops/examples/zerolog%40v0 This snippet demonstrates how to execute a Go example using Zerolog and then pipe its output to 'jq' for JSON processing. It shows two variations: one for general JSON output and another specifically for extracting and formatting the stack trace. ```bash go run examples/zerolog/example.go 2>\&1 | jq go run examples/zerolog/example.go 2>\&1 | jq .stack -r ``` -------------------------------- ### Run slog logger example and process with jq Source: https://pkg.go.dev/github.com/samber/oops/examples/slog Demonstrates how to run the slog logger example and pipe its output to the 'jq' command for JSON processing. This is useful for inspecting structured log data. ```bash go run examples/slog/example.go | jq go run examples/slog/example.go | jq .error.stacktrace -r ``` -------------------------------- ### Run Slog Logger Example with jq (Go) Source: https://pkg.go.dev/github.com/samber/oops/examples/slog_tab=importedby Demonstrates how to run the slog logger example from the "oops" package and pipe its output to `jq` for formatted JSON output. This is useful for inspecting structured logs. ```bash go run examples/slog/example.go | jq ``` -------------------------------- ### Go: Installing the samber/oops library Source: https://pkg.go.dev/github.com/samber/oops/%40v1 This Go command shows how to install the samber/oops library using the go get command. The library is version 1 and adheres to SemVer, ensuring no breaking changes before v2.0.0. It has no external dependencies beyond the Go standard library. ```bash go get github.com/samber/oops ``` -------------------------------- ### Run Logrus Example with Oops Source: https://pkg.go.dev/github.com/samber/oops/examples/logrus_tab=versions This snippet demonstrates how to run the Logrus logger example provided by the oops package and process its output using `jq`. It shows commands to view the full JSON output and specifically extract the stack trace. ```bash go run examples/logrus/example.go 2>\&1 | jq go run examples/logrus/example.go 2>\&1 | jq .stacktrace -r ``` -------------------------------- ### Print Sources Example in Go Source: https://pkg.go.dev/github.com/samber/oops/examples/sources This Go code snippet demonstrates how to print sources from the amber/oops package. It is designed to be piped to `jq` for JSON processing. The example focuses on accessing error sources. ```bash go run examples/sources/example.go | jq go run examples/sources/example.go | jq .error.sources -r ``` -------------------------------- ### Run Panic Example and Parse Output Source: https://pkg.go.dev/github.com/samber/oops/examples/panic Executes the panic example Go program and pipes its output to jq for JSON parsing. The second command specifically extracts and formats the stacktrace from the JSON output. ```bash go run examples/panic/example.go 2>&1 | jq go run examples/panic/example.go 2>&1 | jq .stacktrace -r ``` -------------------------------- ### Run Go example with panic handling and pipe to jq Source: https://pkg.go.dev/github.com/samber/oops/examples/panic%40v0 This command runs a Go example file, redirects standard error to standard output, and pipes the output to 'jq' for JSON processing. It's useful for analyzing structured error output, particularly stack traces. ```shell go run examples/panic/example.go 2>\&1 | jq ``` -------------------------------- ### Zerolog Configuration and Error Logging Example Source: https://pkg.go.dev/github.com/samber/oops/loggers/zerolog_tab=importedby Demonstrates how to configure Zerolog to use Oops's custom marshallers and provides an example of logging an Oops error with a stack trace. ```APIDOC ## Zerolog Configuration and Error Logging Example ### Description This snippet shows how to set up Zerolog with Oops's custom marshallers and log an error that includes context and a stack trace. ### Method N/A (Illustrative Code) ### Endpoint N/A ### Parameters N/A ### Request Example ```go import ( "os" "github.com/rs/zerolog" "github.com/samber/oops" oopszerolog "github.com/samber/oops/loggers/zerolog" ) func main() { // Configure Zerolog to use Oops's marshallers zerolog.ErrorStackMarshaler = oopszerolog.OopsStackMarshaller zerolog.ErrorMarshalFunc = oopszerolog.OopsMarshalFunc // Example query and duration (replace with actual values) query := "SELECT * FROM users" queryDuration := "10ms" // Create an Oops error with context err := oops. With("driver", "postgresql"). With("query", query). With("query.duration", queryDuration). Errorf("could not fetch user") if err != nil { // Log the error using Zerolog, including the stack trace zerolog.New(os.Stderr).Error().Stack().Err(err).Msg(err.Error()) } } ``` ### Response #### Success Response (200) N/A (This is a code example, not an API call) #### Response Example N/A ``` -------------------------------- ### Install Oops library Source: https://pkg.go.dev/github.com/samber/oops/index Command to install the 'oops' library using go get. This library is version 1 and strictly follows SemVer, with no breaking API changes expected before v2.0.0. It has no dependencies outside the Go standard library. ```bash go get github.com/samber/oops ``` -------------------------------- ### Extract stack trace from Logrus example using jq Source: https://pkg.go.dev/github.com/samber/oops/examples/logrus_tab=imports This command demonstrates how to specifically extract the stack trace information from the output of the Logrus example program. It uses `jq` with the `-r` flag (raw output) to print the stack trace as a plain string, making it easier to read and analyze. ```shell go run examples/logrus/example.go 2>&1 | jq .stacktrace -r ``` -------------------------------- ### Example Usage of GinOopsRecovery Middleware Source: https://pkg.go.dev/github.com/samber/oops/recovery/gin This example illustrates how to use the GinOopsRecovery middleware in a Gin application. It includes setting up the router, applying the middleware, defining a route that intentionally panics, and a subsequent middleware to handle the recovered errors. ```go router := gin.New() router.Use(oopsrecoverygin.GinOopsRecovery()) router.GET("/api/users", func(c *gin.Context) { // This panic will be caught and converted to an oops error panic("something went wrong") }) // Handle the recovered error in your error middleware router.Use(func(c *gin.Context) { c.Next() if len(c.Errors) > 0 { // Log or handle the recovered error for _, err := range c.Errors { log.Printf("Recovered error: %+v", err) } } }) ``` -------------------------------- ### Run and Process Segfault Example (Go, Shell) Source: https://pkg.go.dev/github.com/samber/oops/examples/segfault This snippet shows how to execute a Go example program that simulates a segfault and then pipe its output to 'jq' for structured processing. The first command captures all output, while the second specifically extracts the 'stacktrace' field in raw format. This is useful for analyzing segfaults in a reproducible manner. ```shell go run examples/segfault/example.go 2>&1 | jq go run examples/segfault/example.go 2>&1 | jq .stacktrace -r ``` -------------------------------- ### Extract stacktrace from panic example using jq Source: https://pkg.go.dev/github.com/samber/oops/examples/panic%40v0 This command executes a Go example, pipes its output to 'jq', and specifically extracts the '.stacktrace' field, displaying it as raw text. This is useful for isolating and viewing the stack trace from structured error messages. ```shell go run examples/panic/example.go 2>\&1 | jq .stacktrace -r ``` -------------------------------- ### Install Dev Dependencies and Run Tests (Shell) Source: https://pkg.go.dev/github.com/samber/oops/index_tab=imports This snippet shows basic shell commands for managing Go project development dependencies and running tests. It assumes the presence of a 'Makefile' with defined targets for 'tools' and 'test'. ```shell # Install some dev dependencies make tools # Run tests make test ``` -------------------------------- ### Go: Example: Using WithBuilder and FromContext Source: https://pkg.go.dev/github.com/samber/oops/index_tab=versions This example demonstrates how to use WithBuilder to add an OopsErrorBuilder to a request context and then retrieve it using FromContext within a handler to create a formatted error. ```go func middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { builder := oops. Trace(r.Header.Get("X-Request-ID")). With("user_agent", r.UserAgent()) ctx := oops.WithBuilder(r.Context(), builder) next.ServeHTTP(w, r.WithContext(ctx)) }) } func handler(w http.ResponseWriter, r *http.Request) { err := oops.FromContext(r.Context()). In("handler"). Errorf("something went wrong") ``` -------------------------------- ### Install development dependencies in Go Source: https://pkg.go.dev/github.com/samber/oops/%40v0 Command to install necessary development dependencies for the project using Make. This is typically used to set up the local development environment for building and testing the Go package. ```bash # Install some dev dependencies make tools ``` -------------------------------- ### Go Panic Example - github.com/samber/oops/examples/panic Source: https://pkg.go.dev/github.com/samber/oops/examples/panic_tab=importedby This Go code snippet demonstrates how to intentionally cause a panic within a program using the 'panic' function. It's part of the examples for the 'oops' library, likely showing error handling or recovery mechanisms. The code itself does not have external dependencies beyond standard Go. ```go package main import ( "fmt" "github.com/samber/oops" ) func main() { defer func() { if r := recover(); r != nil { fmt.Printf("Recovered from panic: %v\n", r) } }() // Simulate a panic panic("something went wrong") // This line will not be reached fmt.Println("This will not be printed") } ``` -------------------------------- ### Go: OopsErrorBuilder Initialization Source: https://pkg.go.dev/github.com/samber/oops/index_tab=imports This snippet demonstrates how to initialize an OopsErrorBuilder to start constructing an error. It showcases various methods to attach contextual information such as duration, context, hints, request/response details, and time. ```go oops.Duration(time.Second) oops.FromContext(ctx) oops.Hint("something is wrong") oops.In("domain.com") oops.Owner("user") oops.Public("public_info") oops.Request(req, true) oops.Response(res, true) oops.Since(time.Now()) oops.Span("span_id") oops.Tags("tag1", "tag2") oops.Tenant("tenant_id", map[string]any{"key": "value"}) oops.Time(time.Now()) oops.Trace("trace_id") oops.User("user_id", map[string]any{"key": "value"}) oops.With("key1", "value1") oops.WithContext(ctx, "key2", "value2") ``` -------------------------------- ### Load Frontend Unit Scripts (JavaScript) Source: https://pkg.go.dev/github.com/samber/oops/examples/segfault_tab=licenses This snippet shows how to load frontend JavaScript files using a 'loadScript' function. It includes examples for loading 'main.js' and 'unit.js' from specific paths. ```javascript loadScript('/static/frontend/unit/main.js') ``` ```javascript loadScript('/static/frontend/unit/unit.js') ``` -------------------------------- ### Load Static JavaScript Files Source: https://pkg.go.dev/github.com/samber/oops/examples/zerolog_tab=licenses These script snippets demonstrate how to load static JavaScript files from the '/static/frontend/main/main.js' and '/static/frontend/unit/unit.js' paths using a `loadScript` function. This is a common pattern for managing frontend script includes. ```javascript loadScript('/static/frontend/main/main.js') ``` ```javascript loadScript('/static/frontend/unit/unit.js') ``` -------------------------------- ### Install Go Development Dependencies Source: https://pkg.go.dev/github.com/samber/oops/%40v1 This command installs development dependencies required for the project using the Make build tool. It's a common step in setting up a Go project for development. ```bash make tools ``` -------------------------------- ### Load Frontend Scripts Source: https://pkg.go.dev/github.com/samber/oops/examples/log_tab=imports JavaScript code snippets to load frontend scripts, including 'main.js' and 'unit.js', likely for application or unit testing functionalities. ```javascript loadScript('/static/frontend/unit/main/main.js') ``` ```javascript loadScript('/static/frontend/unit/unit.js') ``` -------------------------------- ### Creating a basic error with Oops Source: https://pkg.go.dev/github.com/samber/oops/index_tab=licenses Demonstrates how to create a new error using the Oops library. This example shows the fundamental way to initialize an error with a message and potentially some initial context. It serves as the entry point for building more complex error structures. ```go import "github.com/samber/oops" func main() { Err := oops.New("Something went wrong") fmt.Println(Err) } ``` -------------------------------- ### Panic recovery with Oops Source: https://pkg.go.dev/github.com/samber/oops/index_tab=versions This example demonstrates how to use Oops to recover from a panic and convert it into a structured error. This is useful for handling unexpected panics gracefully. ```go package main import ( "fmt" "github.com/samber/oops" ) func potentiallyPanickingFunction() { panic("runtime error: index out of range") } func main() { defer func() { if r := recover(); r != nil { err := oops.FromPanic(r, "function execution failed"). With("panic_type", "runtime") fmt.Println(err) } }() potentiallyPanickingFunction() } ``` -------------------------------- ### Go: Integrate Oops with Logrus Logging Source: https://pkg.go.dev/github.com/samber/oops/examples/logrus_tab=licenses This Go code snippet demonstrates how to initialize and use the `logrus` logging library in conjunction with the `oops` error handling package. It covers basic setup and how to create and log errors using both libraries. No external dependencies beyond standard Go and the `logrus` and `oops` libraries are required. ```go package main import ( "fmt" "os" "github.com/samber/oops" log "github.com/sirupsen/logrus" ) func init() { log.SetFormatter(&log.TextFormatter{FullTimestamp: true}) log.SetOutput(os.Stdout) log.SetLevel(log.DebugLevel) } func main() { err := oops.New("operation failed"). WithCode(1). // Add an error code WithStack(true). // Include stack trace WithContext(map[string]any{ "userID": 123, "data": "some value", }). Wrap(fmt.Errorf("underlying error")) log.Error(err) } ``` -------------------------------- ### Error Handling with Slog - Go Source: https://pkg.go.dev/github.com/samber/oops/examples/slog_tab=versions Demonstrates structured error handling using the slog package in Go. This example shows how to create and log errors with context, including an 'Err' field for the underlying error. It requires the 'log/slog' and 'github.com/samber/oops' packages. ```go package main import ( "log/slog" "os" "github.com/samber/oops" ) func main() { log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) // Example of creating and logging an error with context err := oops.New("failed to process request"). WithAttrs(slog.String("requestID", "abc-123")). With("userID", 456). WithErr(oops.Errorf("invalid input: %s", "missing field")). Log(log, "error") if err != nil { log.Error("An error occurred", "details", err.Error()) } } ``` -------------------------------- ### Zerolog Formatter Initialization Source: https://pkg.go.dev/github.com/samber/oops/loggers/zerolog%40v0 This section shows how to initialize the Zerolog error stack and error marshaller with the Oops library's formatters. This setup ensures that errors logged by Zerolog will include the rich context and stack traces provided by Oops. ```APIDOC ## Zerolog Formatter Initialization ### Description Initializes Zerolog to use Oops's stack and error marshallers for structured error logging. ### Usage Call this function during your application's initialization phase. ### Code Example ```go import ( oopszerolog "github.com/samber/oops/loggers/zerolog" "github.com/rs/zerolog" "os" ) func init() { zerolog.ErrorStackMarshaler = oopszerolog.OopsStackMarshaller zerolog.ErrorMarshalFunc = oopszerolog.OopsMarshalFunc } ``` ``` -------------------------------- ### Logrus formatter for Oops in Gin Source: https://pkg.go.dev/github.com/samber/oops/recovery/gin This snippet demonstrates how to integrate the GinOopsRecovery middleware into a Gin application using logrus for logging. It shows the basic setup of a Gin router and the application of the middleware. ```go import ( "github.com/gin-gonic/gin" oopsrecoverygin "github.com/samber/oops/recovery/gin" ) func main() { router := gin.New() router.Use(gin.Logger()) router.Use(oopsrecoverygin.GinOopsRecovery()) // ... other middleware and routes } ``` -------------------------------- ### Quick start for Oops error handling in Go Source: https://pkg.go.dev/github.com/samber/oops/index Demonstrates how to use the 'oops' library for composing structured errors with contextual attributes and stack traces. It shows simple error creation with context and error wrapping, highlighting how 'oops.OopsError' implements the standard 'error' interface. ```go import "github.com/samber/oops" func main() { // Simple error with context err := oops. In("user-service"). Tags("database", "postgres"). Code("network_failure"). User("user-123", "email", "foo@bar.com"). With("path", "/hello/world"). Errorf("failed to fetch user: %s", "connection timeout") // Error wrapping if err != nil { return oops. Trace("req-123"). With("product_id", "456"). Wrapf(err, "user operation failed") } } ``` -------------------------------- ### Go: Create OopsErrorBuilder from various contexts Source: https://pkg.go.dev/github.com/samber/oops/index_tab=versions These functions initialize an OopsErrorBuilder, allowing you to start chaining error details. They can capture context from durations, HTTP requests/responses, and Go contexts. ```go func Duration(duration time.Duration) OopsErrorBuilder func FromContext(ctx context.Context) OopsErrorBuilder func Request(req *http.Request, withBody bool) OopsErrorBuilder func Response(res *http.Response, withBody bool) OopsErrorBuilder func WithContext(ctx context.Context, keys ...any) OopsErrorBuilder ``` -------------------------------- ### Run example.go with jq Source: https://pkg.go.dev/github.com/samber/oops/examples/sources_tab=importedby This command executes the example.go script from the examples/sources directory and pipes its output to jq for pretty-printing. It's useful for inspecting the JSON output of the script. ```shell go run examples/sources/example.go | jq ``` -------------------------------- ### Performing assertions with Oops in Go Source: https://pkg.go.dev/github.com/samber/oops/index_tab=licenses Provides examples of using assertion helpers from the Oops library. These helpers simplify validation logic by allowing concise checks for conditions, returning specific errors if assertions fail. This leads to cleaner and more readable validation code. ```go import "github.com/samber/oops" func validateInput(value int) error { return oops.Assert(value > 0, "Value must be positive").With("inputValue", value) } ``` -------------------------------- ### OopsError Methods: StackFrames, Stacktrace, Tags, Tenant, Time, ToMap, Trace, Unwrap Source: https://pkg.go.dev/github.com/samber/oops/index_tab=licenses These methods are part of the OopsError type and allow retrieval of specific error details. For example, StackFrames() provides call stack information, while Tags() returns associated key-value pairs. Unwrap() is used to get the underlying error. ```go func (e *OopsError) StackFrames() []Frame func (e *OopsError) Stacktrace() string func (e *OopsError) Tags() map[string]any func (e *OopsError) Tenant() string func (e *OopsError) Time() time.Time func (e *OopsError) ToMap() map[string]any func (e *OopsError) Trace() error func (e *OopsError) Unwrap() error ``` -------------------------------- ### Go: Handling panics with oops Source: https://pkg.go.dev/github.com/samber/oops/%40v1 Provides an example of how to gracefully recover from a panic using the oops library's panic handling capabilities. This prevents application crashes and allows for logging or wrapping the panic as an error. ```go package main import ( "fmt" "github.com/samber/oops" ) func mayPanic() { panic("critical failure") } func main() { defer func() { if r := recover(); r != nil { err := oops.FromPanic(r).Wrap(nil, "An operation panicked"). WithStackTrace(oops.Caller(0)) fmt.Println(err.Error()) } }() mayPanic() } ``` -------------------------------- ### Logrus Formatter Integration Source: https://pkg.go.dev/github.com/samber/oops/loggers/logrus_tab=imports This section explains how to integrate the Oops Logrus formatter into your existing Logrus logger setup. It shows the necessary import and initialization steps. ```APIDOC ## Logrus Formatter Integration ### Description This endpoint details how to integrate the Oops Logrus formatter with your application's logger. ### Method Initialization (not an HTTP method, but a code setup process) ### Endpoint N/A (Code initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go import oopslogrus "github.com/samber/oops/loggers/logrus" func init() { logrus.SetFormatter( oopslogrus.NewOopsFormatter( &logrus.JSONFormatter{}, ) ) } ``` ### Response #### Success Response N/A (This is a code initialization example, not an API response) #### Response Example N/A ``` -------------------------------- ### Basic Error Creation in Go Source: https://pkg.go.dev/github.com/samber/oops/%40v1 A simple example of creating an error using the Errorf function from the oops library. This generates an error with a basic message and includes stack trace information. ```go err1 := oops.Errorf("could not fetch user") ``` -------------------------------- ### Extract Slog Logger Error Stacktrace with jq (Go) Source: https://pkg.go.dev/github.com/samber/oops/examples/slog_tab=importedby Shows how to extract the error stacktrace from the slog logger example output using `jq`. This command specifically targets the `.error.stacktrace` field and outputs it as a raw string. ```bash go run examples/slog/example.go | jq .error.stacktrace -r ``` -------------------------------- ### Efficient Error Wrapping with Wrapf (Go) Source: https://pkg.go.dev/github.com/samber/oops/%40v1 Provides a concise example of using oops.Wrapf to wrap errors, highlighting its efficiency by returning nil if the wrapped error is nil. This avoids unnecessary nil checks. It requires the 'oops' package. ```go return oops.Wrapf(mayFail(), "...") ``` -------------------------------- ### Initialize Zerolog with Oops Formatters (Go) Source: https://pkg.go.dev/github.com/samber/oops/loggers/zerolog This Go code snippet demonstrates how to integrate the oopszerolog package with Zerolog. It sets custom marshallers for Zerolog's error handling to correctly format Oops errors, including their context and stack traces. This setup ensures that when an error is logged using Zerolog, the Oops error details are preserved in a structured format. ```go import ( oopszerolog "github.com/samber/oops/loggers/zerolog" "github.com/rs/zerolog" "os" "github.com/samber/oops" ) func init() { zerolog.ErrorStackMarshaler = oopszerolog.OopsStackMarshaller zerolog.ErrorMarshalFunc = oopszerolog.OopsMarshalFunc } func main() { var query string var queryDuration int err := oops. With("driver", "postgresql"). With("query", query). With("query.duration", queryDuration). Errorf("could not fetch user") if err != nil { zerolog.New(os.Stderr).Error().Stack().Err(err).Msg(err.Error()) } } ``` -------------------------------- ### Go: Example of using oops for structured error handling Source: https://pkg.go.dev/github.com/samber/oops/%40v1 This Go code demonstrates how to use the samber/oops library to create structured errors. It shows error wrapping, adding context like user ID, role, and tags, and logging the structured error. This approach enhances error visibility and debugging. ```go func d() error { return oops. Code("iam_missing_permission"). In("authz"). Tags("authz"). Time(time.Now()). With("user_id", 1234). With("permission", "post.create"). Hint("Runbook: https://doc.acme.org/doc/abcd.md"). User("user-123", "firstname", "john", "lastname", "doe"). Errorf("permission denied") } func c() error { return d() } func b() error { // add more context return oops. In("iam"). Tags("iam"). Trace("e76031ee-a0c4-4a80-88cb-17086fdd19c0"). With("hello", "world"). Wrapf(c(), "something failed") } func a() error { return b() } func main() { logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) err := a() if err != nil { logger.Error( err.Error(), slog.Any("error", err), // unwraps and flattens error context ) } } ``` -------------------------------- ### Go: Error Wrapping and Panic Recovery with oops Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby Illustrates advanced error handling patterns in Go using the 'oops' library, including wrapping errors from database operations and recovering from panics with contextual information. It also shows how to use assertions for validating conditions. ```go // with error wrapping err0 := oops. In("repository"). Tags("database", "sql"). Wrapf(sql.Exec(query), "could not fetch user") // Wrapf returns nil when sql.Exec() is nil // with panic recovery err1 := oops. In("repository"). Tags("database", "sql"). Recover(func () { panic("caramba!") }) // with assertion err2 := oops. In("repository"). Tags("database", "sql"). Recover(func () { // ... oops.Assertf(time.Now().Weekday() == 1, "This code should run on Monday only.") // ... }) // oops.New err3 := oops. In("repository"). Tags("database", "sql"). New("an error message") // oops.Errorf err3 := oops. ``` -------------------------------- ### Initialize Logrus with Oops Formatter (Go) Source: https://pkg.go.dev/github.com/samber/oops/loggers/logrus_tab=importedby This Go code snippet demonstrates how to initialize the Logrus logger with the custom Oops formatter. It imports the necessary packages and sets the formatter to use the NewOopsFormatter, wrapping a standard JSONFormatter. This setup is typically done in an init function to ensure the formatter is applied when the package is loaded. ```go import oopslogrus "github.com/samber/oops/loggers/logrus" func init() { logrus.SetFormatter( oopslogrus.NewOopsFormatter( &logrus.JSONFormatter{}, ) ) } func main() { err := oops. ``` -------------------------------- ### Build Errors with Hints and Ownership in Go Source: https://pkg.go.dev/github.com/samber/oops/index_tab=imports Demonstrates creating an error with additional context like hints for developers and ownership information. This is useful for debugging complex issues by providing actionable advice and identifying responsible teams. ```go err5 := oops. Hint("The user could have been removed. Please check deleted_at column."). Owner("Slack: #api-gateway"). Errorf("could not fetch user") ``` -------------------------------- ### Get Deprecated Log Valuer with OopsError Go Source: https://pkg.go.dev/github.com/samber/oops/index The `LogValuer` method on an `OopsError` provides a deprecated way to get a structured value for logging. It's recommended to use `LogValue` instead for modern logging practices. This method is part of the `OopsError` interface. ```Go func (o OopsError) LogValuer() slog.Valuedeprecated ``` -------------------------------- ### Logging an Error with Oops and Zerolog Source: https://pkg.go.dev/github.com/samber/oops/loggers/zerolog%40v0 Demonstrates how to create and log an error using Oops, and then log it with Zerolog, leveraging the previously configured formatters to include context and stack traces. ```APIDOC ## Logging an Error with Oops and Zerolog ### Description Creates an error with context using Oops and logs it using Zerolog, which will automatically format the error with its context and stack trace. ### Method `main` function demonstrating error creation and logging. ### Code Example ```go import ( "os" "github.com/rs/zerolog" "github.com/samber/oops" ) func main() { query := "SELECT * FROM users" queryDuration := "100ms" err := oops. With("driver", "postgresql"). With("query", query). With("query.duration", queryDuration). Errorf("could not fetch user") if err != nil { zerolog.New(os.Stderr).Error().Stack().Err(err).Msg(err.Error()) } } ``` ``` -------------------------------- ### Adding stack trace to an error Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby This example shows how to attach a stack trace to an existing error using the 'oops' library. The stack trace provides function call information at the point where the error was created or wrapped, aiding in debugging. ```go package main import ( "fmt" "github.com/samber/oops" ) func faultyOperation() error { return oops.New("failed in operation"). WithStack(oops.Caller(0)) } func main() { err := faultyOperation() fmt.Println(err.Error()) } ``` -------------------------------- ### Get Error Timestamp (Go) Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby The Time method returns the timestamp of when the OopsError occurred, retrieving it from the deepest error in the chain. ```Go func (o OopsError) Time() time.Time { // ... implementation details ... } ``` -------------------------------- ### Get Tenant ID and Data (Go) Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby The Tenant method returns the tenant ID and its associated data from the deepest error in the OopsError chain. ```Go func (o OopsError) Tenant() (string, map[string]any) { // ... implementation details ... } ``` -------------------------------- ### Go: Create Error with Optional User and Tenant Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby Demonstrates creating an error that includes both optional user information and tenant details. This is useful in multi-tenant applications for context-specific error tracking. ```go err8 := oops. User(userID, "firstname", "Samuel"). Tenant(workspaceID, "name", "my little project"). Errorf("could not fetch user") ``` -------------------------------- ### Get Unique Tags (Go) Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby The Tags method retrieves all unique tags associated with an OopsError, merging and deduplicating tags from all errors in the error chain. ```Go func (o OopsError) Tags() []string { // ... implementation details ... } ``` -------------------------------- ### Go: Create Error with Hint and Ownership Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby Demonstrates creating an error with additional hints for developers and specifying ownership. This is useful for debugging complex issues by providing context and responsible parties. ```go err5 := oops. Hint("The user could have been removed. Please check deleted_at column."). Owner("Slack: #api-gateway"). Errorf("could not fetch user") ``` -------------------------------- ### Go: Create Error with Hint and Ownership Source: https://pkg.go.dev/github.com/samber/oops/index_tab=versions Demonstrates creating an error with additional hints for developers and ownership information, specifying the context for debugging. This approach helps in providing richer error information beyond a simple message. ```Go err5 := oops. Hint("The user could have been removed. Please check deleted_at column."). Owner("Slack: #api-gateway"). Errorf("could not fetch user") ``` -------------------------------- ### Get Error Timestamp - Go Source: https://pkg.go.dev/github.com/samber/oops/%40v0 The Time method returns the timestamp indicating when the error occurred. This timestamp is retrieved from the most deeply nested error in the error chain. ```Go func (o OopsError) Time() time.Time { // Implementation details... return time.Time{} } ``` -------------------------------- ### Get Raw Stack Frames (Go) Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby The StackFrames method returns the raw stack frames of an OopsError as runtime.Frame objects. This is useful for custom stack trace formatting or analysis. ```Go func (o OopsError) StackFrames() []runtime.Frame { // ... implementation details ... } ``` -------------------------------- ### Creating a basic error with Oops Source: https://pkg.go.dev/github.com/samber/oops/index_tab=versions This snippet demonstrates how to create a new error using the Oops library. It shows the basic initialization of an error with a message and optional context. ```go package main import ( "fmt" "github.com/samber/oops" ) func main() { err := oops.New("Something went wrong") fmt.Println(err) } ``` -------------------------------- ### Get Tenant Info - Go Source: https://pkg.go.dev/github.com/samber/oops/%40v0 The Tenant method returns the tenant ID and any associated tenant-specific data. It extracts this information from the deepest error within the error chain. ```Go func (o OopsError) Tenant() (string, map[string]any) { // Implementation details... return "", nil } ``` -------------------------------- ### Extract error sources with jq Source: https://pkg.go.dev/github.com/samber/oops/examples/sources_tab=importedby This command runs the example.go script and specifically extracts the 'error.sources' field from the JSON output using jq with the -r flag for raw output. This is helpful for isolating and viewing error source details. ```shell go run examples/sources/example.go | jq .error.sources -r ``` -------------------------------- ### Get Tenant from OopsError in Go Source: https://pkg.go.dev/github.com/samber/oops/%40v1 The Tenant method retrieves the tenant information associated with an OopsError. This is likely used in multi-tenant applications to identify the context of the error. ```Go func (o OopsError) Tenant() string ``` -------------------------------- ### Log Oops Error with Context Source: https://pkg.go.dev/github.com/samber/oops/loggers/logrus_tab=importedby Logs an error message with context using the oops formatter for logrus. This example demonstrates how to add specific key-value pairs to the error context before logging. ```go import ( "github.com/samber/oops" "github.com/sirupsen/logrus" ) func logErrorWithContext(query string, queryDuration int) { // Assume 'err' is an initialized oops.OopsError object var err error // Example of adding context to an oops error before logging // In a real scenario, 'err' would likely be populated from a previous operation. // For demonstration, let's create a placeholder: // This part is illustrative, as the actual creation of 'err' would depend on the application logic. // The provided snippet only shows the logging part. // Hypothetical error creation and context addition: // err = oops.Errorf("could not fetch user") // err = err.With("driver", "postgresql") // err = err.With("query", query) // err = err.With("query.duration", queryDuration) // The following lines show how you would log such an error if 'err' was properly initialized: // logrus.WithError(err).Error(err.Error()) // This line is from the original text, assuming 'err' is already defined and populated. // If we were to use the oops formatter, the logging might look like this: // logger.WithError(err).Error("error fetching user details") // Assuming logger is configured with oopslogrus.NewOopsFormatter // The provided snippet focuses on how to *add* context using .With() methods on an oops.OopsError, // and then how to log it using logrus. The code below is based on the text snippet provided, // showing the usage of .With() and then a hypothetical logrus logging statement. var oopsErr error oopsErr = oops.Errorf("could not fetch user") oopsErr = oops.With(oopsErr, "driver", "postgresql") oopsErr = oops.With(oopsErr, "query", query) oopsErr = oops.With(oopsErr, "query.duration", queryDuration) // Assuming logrus is configured with oopslogrus formatter: // logrus.WithError(oopsErr).Error(oopsErr.Error()) } ``` -------------------------------- ### Error Creation and Formatting Source: https://pkg.go.dev/github.com/samber/oops/index_tab=imports Functions for creating and formatting errors. ```APIDOC ## Errorf ### Description Creates a new error with a formatted message. ### Method N/A (Function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go err := oops.Errorf("user %d not found", userID) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` ```APIDOC ## New ### Description Creates a new error with a simple message. ### Method N/A (Function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go err := oops.New("database connection failed") ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Log an Oops Error with Zerolog and Stack Trace Source: https://pkg.go.dev/github.com/samber/oops/loggers/zerolog_tab=importedby Demonstrates creating and logging an 'oops' error using zerolog. The error includes contextual information like 'driver' and 'query'. If an error occurs, it's logged with a stack trace using zerolog. ```go err := oops. With("driver", "postgresql"). With("query", query). With("query.duration", queryDuration). Errorf("could not fetch user") if err != nil { zerolog.New(os.Stderr).Error().Stack().Err(err).Msg(err.Error()) } ``` -------------------------------- ### Go: Get Debugging Hint for Error Source: https://pkg.go.dev/github.com/samber/oops/index_tab=versions The Hint method returns a debugging hint for resolving an error. It retrieves the hint from the deepest error in the chain, aiding in error diagnosis. ```Go func (o OopsError) Hint() string { // Implementation details... return "" } ``` -------------------------------- ### Create Simple Errors with Oops Go Library Source: https://pkg.go.dev/github.com/samber/oops/index Demonstrates creating basic errors with and without public-facing messages and stack traces using the oops library. ```go // simple error with public facing message err0 := oops. Public("Could not fetch user."). Errorf("sql: bad connection") // simple error with stacktrace err1 := oops.New("could not fetch user") ``` -------------------------------- ### Get Unique Tags - Go Source: https://pkg.go.dev/github.com/samber/oops/%40v0 The Tags method retrieves all unique tags associated with an OopsError and its underlying error chain. Tags are consolidated from all errors in the chain and automatically deduplicated. ```Go func (o OopsError) Tags() []string { // Implementation details... return nil } ``` -------------------------------- ### Go: Create and Format Errors with Oops Source: https://pkg.go.dev/github.com/samber/oops/index_tab=versions This snippet demonstrates how to create and format errors using the oops package. It includes functions like `Errorf` for formatted error creation and `New` for basic error instantiation. These functions are essential for building detailed error messages. ```go package main import ( "fmt" "github.com/samber/oops" ) func main() { // Example of creating a formatted error err := oops.Errorf("failed to process item: %s", "item123") fmt.Println(err) // Example of creating a simple error errSimple := oops.New("a general error occurred") fmt.Println(errSimple) } ``` -------------------------------- ### Go: Basic Error Creation and Wrapping with Oops Source: https://pkg.go.dev/github.com/samber/oops/%40v0 Demonstrates how to create a new error using the Oops library and how to wrap existing errors with additional context. This showcases the library's core functionality for structured error handling. ```Go package main import ( "fmt" "github.com/samber/oops" ) func main() { // Create a new error with context err := oops.New("operation failed"). WithKind(oops.KindBadGateway). WithContextO("request_id", "abc-123"). WithContextO("user", "alice") fmt.Println(err) // Wrap an existing error with more context wrappedErr := oops.Wrap(err). WithKind(oops.KindInternal). WithContextO("step", "processing_data") fmt.Println(wrappedErr) } ``` -------------------------------- ### Get User Info from OopsError Source: https://pkg.go.dev/github.com/samber/oops/index_tab=licenses The User method retrieves the user ID and any associated user data from an OopsError. It fetches this information from the deepest error within the error's chain. This is useful for contextualizing errors with user-specific details. ```go func (o OopsError) User() (string, map[string]any) { // Implementation details to retrieve user ID and data } ``` -------------------------------- ### Run tests for Go package Source: https://pkg.go.dev/github.com/samber/oops/%40v0 Command to execute the test suite for the Go package using Make. This ensures that the code changes do not introduce regressions and that the package functions as expected. ```bash # Run tests make test ``` -------------------------------- ### Get Formatted Stack Trace (Go) Source: https://pkg.go.dev/github.com/samber/oops/index_tab=importedby The Stacktrace method returns a formatted string representation of an OopsError's stack trace. It excludes frames from the Go standard library and the oops package itself. ```Go func (o OopsError) Stacktrace() string { // ... implementation details ... } ``` -------------------------------- ### Get Error Sources Go Source: https://pkg.go.dev/github.com/samber/oops/index The `Sources` method on an `OopsError` returns information about the sources of the error. This can be helpful in tracing the origin of problems in distributed systems. This method is part of the `OopsError` interface. ```Go func (o OopsError) Sources() string ```