mirror of
https://github.com/openimsdk/open-im-server.git
synced 2026-04-28 14:29:19 +08:00
refactor: 3.7.0 code conventions. (#2148)
* Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * feat: add code lint * feat: add code lint * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * Script Refactoring * feat: code format * Script Refactoring * Script Refactoring * Script Refactoring * Adjust MinIO configuration settings * Adjust configuration settings * Adjust configuration settings * refactor: config change. * refactor: webhooks update. * Adjust configuration settings * refactor: webhooks update. * Adjust configuration settings * Adjust configuration settings * Adjust configuration settings * feat: s3 api addr * refactor: webhooks update. * Adjust configuration settings * Adjust configuration settings * Adjust configuration settings * Adjust configuration settings * Adjust configuration settings * Adjust configuration settings * Adjust configuration settings * refactor: webhooks update. * refactor: kafka update. * Simplify the Docker Compose configuration, remove unnecessary environment variables, and eliminate the gateway service. * refactor: kafka update. * refactor: kafka update. * Simplify the Docker Compose configuration, remove unnecessary environment variables, and eliminate the gateway service. * Simplify the Docker Compose configuration, remove unnecessary environment variables, and eliminate the gateway service. * Windows can compile and run. * Windows can compile and run. * refactor: kafka update. * feat: msg cache split * refactor: webhooks update * refactor: webhooks update * refactor: friends update * refactor: group update * refactor: third update * refactor: api update * refactor: crontab update * refactor: msggateway update * mage * mage * refactor: all module update. * check * refactor: all module update. * load config * load config * load config * load config * refactor: all module update. * refactor: all module update. * refactor: all module update. * refactor: all module update. * refactor: all module update. * Optimize Docker configuration and script. * refactor: all module update. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * refactor: all module update. * Optimize Docker configuration and script. * refactor: all module update. * refactor: all module update. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * update tools * update tools * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * update protocol * Optimize Docker configuration and script. * Optimize Docker configuration and script. * refactor: all module update. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * Optimize Docker configuration and script. * refactor: api remove token auth by redis directly. * Code Refactoring * refactor: websocket auth change to call rpc of auth. * refactor: kick online user and remove token change to call auth rpc. * refactor: kick online user and remove token change to call auth rpc. * refactor: remove msggateway redis. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor webhook * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor webhook * refactor: cmd update. * refactor: cmd update. * fix: runtime: goroutine stack exceeds * refactor: cmd update. * refactor notification * refactor notification * refactor * refactor: cmd update. * refactor: cmd update. * refactor * refactor * refactor * protojson * protojson * protojson * go mod * wrapperspb * refactor: cmd update. * refactor: cmd update. * refactor: cmd update. * refactor: context update. * refactor: websocket update info. * refactor: websocket update info. * refactor: websocket update info. * refactor: websocket update info. * refactor: api name change. * refactor: debug info. * refactor: debug info. * refactor: debug info. * fix: update file * refactor * refactor * refactor: debug info. * refactor: debug info. * refactor: debug info. * refactor: debug info. * refactor: debug info. * refactor: debug info. * fix: callback update. * fix: callback update. * refactor * fix: update message. * fix: msg cache timeout. * refactor * refactor * fix: push update. * fix: push update. * fix: push update. * fix: push update. * fix: push update. * fix: push update. * fix: push update. * fix: websocket handle error remove when upgrade error. --------- Co-authored-by: skiffer-git <44203734@qq.com> Co-authored-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com> Co-authored-by: withchao <993506633@qq.com>
This commit is contained in:
+89
-26
@@ -115,22 +115,83 @@ var s = F()
|
||||
func F() string { return "A" }
|
||||
```
|
||||
|
||||
- Use `_` as a prefix for unexported top-level constants and variables.
|
||||
- This example emphasizes using PascalCase for exported constants and camelCase for unexported ones, avoiding all caps and underscores.
|
||||
|
||||
```go
|
||||
// bad
|
||||
const (
|
||||
defaultHost = "127.0.0.1"
|
||||
defaultPort = 8080
|
||||
MAX_COUNT = 100
|
||||
timeout = 30
|
||||
)
|
||||
|
||||
// good
|
||||
const (
|
||||
_defaultHost = "127.0.0.1"
|
||||
_defaultPort = 8080
|
||||
MaxCount = 100 // Exported constants should use PascalCase.
|
||||
defaultTimeout = 30 // Unexported constants should use camelCase.
|
||||
)
|
||||
```
|
||||
|
||||
- Grouping related constants enhances organization and readability, especially when there are multiple constants related to a particular feature or configuration.
|
||||
|
||||
```go
|
||||
// bad
|
||||
const apiVersion = "v1"
|
||||
const retryInterval = 5
|
||||
|
||||
// good
|
||||
const (
|
||||
ApiVersion = "v1" // Group related constants together for better organization.
|
||||
RetryInterval = 5
|
||||
)
|
||||
```
|
||||
|
||||
- The "good" practice utilizes iota for a clear, concise, and auto-incrementing way to define enumerations, reducing the potential for errors and improving maintainability.
|
||||
|
||||
```go
|
||||
// bad
|
||||
const (
|
||||
StatusActive = 0
|
||||
StatusInactive = 1
|
||||
StatusUnknown = 2
|
||||
)
|
||||
|
||||
// good
|
||||
const (
|
||||
StatusActive = iota // Use iota for simple and efficient constant enumerations.
|
||||
StatusInactive
|
||||
StatusUnknown
|
||||
)
|
||||
```
|
||||
|
||||
- Specifying types explicitly improves clarity, especially when the purpose or type of a constant might not be immediately obvious. Additionally, adding comments to exported constants or those whose purpose isn't clear from the name alone can greatly aid in understanding the code.
|
||||
|
||||
```go
|
||||
// bad
|
||||
const serverAddress = "localhost:8080"
|
||||
const debugMode = 1 // Is this supposed to be a boolean or an int?
|
||||
|
||||
// good
|
||||
const ServerAddress string = "localhost:8080" // Specify type for clarity.
|
||||
// DebugMode indicates if the application should run in debug mode (true for debug mode).
|
||||
const DebugMode bool = true
|
||||
```
|
||||
|
||||
- By defining a contextKey type and making userIDKey of this type, you avoid potential collisions with other context keys. This approach leverages Go's type system to provide compile-time checks against misuse.
|
||||
|
||||
```go
|
||||
// bad
|
||||
const userIDKey = "userID"
|
||||
|
||||
// In this example, userIDKey is a string type, which can lead to conflicts or accidental misuse because string keys are prone to typos and collisions in a global namespace.
|
||||
|
||||
|
||||
// good
|
||||
type contextKey string
|
||||
|
||||
const userIDKey contextKey = "userID"
|
||||
```
|
||||
|
||||
|
||||
- Embedded types (such as mutexes) should be at the top of the field list within the struct, and there must be a blank line separating embedded fields from regular fields.
|
||||
|
||||
```go
|
||||
@@ -274,8 +335,6 @@ The use of `panic` should be carefully controlled in Go applications to ensure p
|
||||
|
||||
- **Restricted Use in Main Package:** In the main package, the use of `panic` should be reserved for situations where the program is entirely inoperable, such as failure to open essential files, inability to connect to the database, or other critical startup issues. Even in these scenarios, prefer using structured error handling to terminate the program.
|
||||
|
||||
- **Use `log.Fatal` for Critical Errors:** Instead of panicking, use `log.Fatal` to log critical errors that prevent the program from operating normally. This approach allows the program to terminate while ensuring the error is properly logged for troubleshooting.
|
||||
|
||||
- **Prohibition on Exportable Interfaces:** Exportable interfaces must not invoke `panic`. They should handle errors gracefully and return errors as part of their contract.
|
||||
|
||||
- **Prefer Errors Over Panic:** It is recommended to use error returns instead of panic to convey errors within a package. This approach promotes error handling that integrates smoothly with Go's error handling idioms.
|
||||
@@ -303,7 +362,7 @@ func SIGTERMExit() {
|
||||
|
||||
```go
|
||||
import (
|
||||
_ "net/http/pprof"
|
||||
_ "net/webhook/pprof"
|
||||
|
||||
"github.com/openimsdk/open-im-server/v3/pkg/common/cmd"
|
||||
util "github.com/openimsdk/open-im-server/v3/pkg/util/genutil"
|
||||
@@ -357,27 +416,31 @@ The naming convention is a very important part of the code specification. A unif
|
||||
- Don't use broad, meaningless package names like common, util, shared or lib.
|
||||
- The package name should be simple and clear, such as net, time, log.
|
||||
|
||||
### 2.2 Function Naming
|
||||
|
||||
- The function name is in camel case, and the first letter is uppercase or lowercase according to the access control decision,For example: `MixedCaps` or `mixedCaps`.
|
||||
- Code automatically generated by code generation tools (such as `xxxx.pb.go`) and underscores used to group related test cases (such as `TestMyFunction_WhatIsBeingTested`) exclude this rule.
|
||||
### 2.2 Function Naming Conventions
|
||||
|
||||
In accordance with the naming conventions adopted by OpenIM and drawing reference from the Google Naming Conventions as per the guidelines available at https://google.github.io/styleguide/go/, the following expectations for naming practices within the project are set forth:
|
||||
Function names should adhere to the following guidelines, inspired by OpenIM’s standards and Google’s Go Style Guide:
|
||||
|
||||
1. **File Names:**
|
||||
+ Both hyphens (`-`) and underscores (`_`) are permitted when naming files.
|
||||
+ A preference is established for the use of underscores (`_`), suggesting it as the best practice in general scenarios.
|
||||
2. **Script and Markdown Files:**
|
||||
+ For shell scripts (bash files) and Markdown (`.md`) documents, the use of hyphens (`-`) is recommended.
|
||||
+ This recommendation is based on the improved searchability and compatibility in web browsers when hyphens are used in names.
|
||||
3. **Directories:**
|
||||
+ A consistent approach is mandated for naming directories, exclusively using hyphens (`-`) to separate words within directory names.
|
||||
- Use camel case for function names. Start with an uppercase letter for public functions (`MixedCaps`) and a lowercase letter for private functions (`mixedCaps`).
|
||||
- Exceptions to this rule include code automatically generated by tools (e.g., `xxxx.pb.go`) and test functions that use underscores for clarity (e.g., `TestMyFunction_WhatIsBeingTested`).
|
||||
|
||||
### 2.3 File and Directory Naming Practices
|
||||
|
||||
To maintain consistency and readability across the OpenIM project, observe the following naming practices:
|
||||
|
||||
**File Names:**
|
||||
- Use underscores (`_`) as the default separator in filenames, keeping them short and descriptive.
|
||||
- Both hyphens (`-`) and underscores (`_`) are allowed, but underscores are preferred for general use.
|
||||
|
||||
**Script and Markdown Files:**
|
||||
- Prefer hyphens (`-`) for shell scripts and Markdown (`.md`) files to enhance searchability and web compatibility.
|
||||
|
||||
**Directories:**
|
||||
- Name directories with hyphens (`-`) exclusively to separate words, ensuring consistency and readability.
|
||||
|
||||
Remember to keep filenames lowercase and use meaningful, concise identifiers to facilitate better organization and navigation within the project.
|
||||
|
||||
|
||||
### 2.3 File Naming
|
||||
|
||||
- Keep the filename short and meaningful.
|
||||
- Filenames should be lowercase and use underscores to separate words.
|
||||
|
||||
### 2.4 Structure Naming
|
||||
|
||||
@@ -478,9 +541,9 @@ var LintGonicMapper = GonicMapper{
|
||||
- If the variable type is bool, the name should start with Has, Is, Can or Allow, for example:
|
||||
|
||||
```go
|
||||
var has Conflict bool
|
||||
var hasConflict bool
|
||||
var isExist bool
|
||||
var can Manage bool
|
||||
var canManage bool
|
||||
var allowGitHook bool
|
||||
```
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
# Go Language Documentation for OpenIM
|
||||
|
||||
In the realm of software development, especially within Go language projects, documentation plays a crucial role in ensuring code maintainability and ease of use. Properly written and accurate documentation is not only essential for understanding and utilizing software effectively but also needs to be easy to write and maintain. This principle is at the heart of OpenIM's approach to supporting commands and generating documentation.
|
||||
|
||||
## Supported Commands in OpenIM
|
||||
|
||||
OpenIM leverages Go language's documentation standards to facilitate clear and maintainable code documentation. Below are some of the key commands used in OpenIM for documentation purposes:
|
||||
|
||||
### `go doc` Command
|
||||
|
||||
The `go doc` command is used to print documentation for Go language entities such as variables, constants, functions, structures, and interfaces. This command allows specifying the identifier of the program entity to tailor the output. Examples of `go doc` command usage include:
|
||||
|
||||
- `go doc sync.WaitGroup.Add` prints the documentation for a specific method of a type in a package.
|
||||
- `go doc -u -all sync.WaitGroup` displays all program entities, including unexported ones, for a specified type.
|
||||
- `go doc -u sync` outputs all program entities for a specified package, focusing on exported ones without detailed comments.
|
||||
|
||||
### `godoc` Command
|
||||
|
||||
For environments lacking internet access, the `godoc` command serves to view the Go language standard library and project dependency library documentation in a web format. Notably, post-Go 1.12 versions, `godoc` is not part of the Go compiler suite. It can be installed using:
|
||||
|
||||
```shell
|
||||
go get -u -v golang.org/x/tools/cmd/godoc
|
||||
```
|
||||
|
||||
The `godoc` command, once running, hosts a local web server (by default on port 6060) to facilitate documentation browsing at http://127.0.0.1:6060. It generates documentation based on the GOROOT and GOPATH directories, showcasing both the project's own documentation and that of third-party packages installed via `go get`.
|
||||
|
||||
### Custom Documentation Generation Commands in OpenIM
|
||||
|
||||
OpenIM includes a suite of commands aimed at initializing, generating, and maintaining project documentation and associated files. Some notable commands are:
|
||||
|
||||
- `gen.init`: Initializes the OpenIM server project.
|
||||
- `gen.docgo`: Generates missing `doc.go` files for Go packages, crucial for package-level documentation.
|
||||
- `gen.errcode.doc`: Generates markdown documentation for OpenIM error codes.
|
||||
- `gen.ca`: Generates CA files for all certificates, enhancing security documentation.
|
||||
|
||||
These commands underscore the project's commitment to thorough and accessible documentation, supporting both developers and users alike.
|
||||
|
||||
## Writing Your Own Documentation
|
||||
|
||||
When creating documentation for Go projects, including OpenIM, it's important to follow certain practices:
|
||||
|
||||
1. **Commenting**: Use single-line (`//`) and block (`/* */`) comments to provide detailed documentation within the code. Block comments are especially useful for package documentation, which should immediately precede the package statement without any intervening blank lines.
|
||||
|
||||
2. **Overview Section**: To create an overview section in the documentation, place a block comment directly before the package statement. This section should succinctly describe the package's purpose and functionality.
|
||||
|
||||
3. **Detailed Descriptions**: Comments placed before functions, structures, or variables will be used to generate detailed descriptions in the documentation. Follow the same commenting rules as for the overview section.
|
||||
|
||||
4. **Examples**: Include example functions prefixed with `Example` to demonstrate usage. Output from these examples can be documented at the end of the function, starting with `// Output:` followed by the expected result.
|
||||
|
||||
Through adherence to these documentation practices, OpenIM ensures that its codebase remains accessible, maintainable, and easy to use for developers and users alike.
|
||||
+128
-7
@@ -66,7 +66,7 @@ The `CodeError` interface is designed to provide a unified mechanism for error h
|
||||
|
||||
## Logging Standards and Code Examples
|
||||
|
||||
In the OpenIM project, we use the unified logging package `github.com/OpenIMSDK/tools/log` for logging to achieve efficient log management and analysis. This logging package supports structured logging formats, making it easier for developers to handle log information.
|
||||
In the OpenIM project, we use the unified logging package `github.com/openimsdk/tools/log` for logging to achieve efficient log management and analysis. This logging package supports structured logging formats, making it easier for developers to handle log information.
|
||||
|
||||
### Logger Interface and Implementation
|
||||
|
||||
@@ -96,7 +96,7 @@ func main() {
|
||||
|
||||
## Error Handling and Code Examples
|
||||
|
||||
We use the `github.com/OpenIMSDK/tools/errs` package for unified error handling and wrapping.
|
||||
We use the `github.com/openimsdk/tools/errs` package for unified error handling and wrapping.
|
||||
|
||||
### CodeError Interface and Implementation
|
||||
|
||||
@@ -121,7 +121,7 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/OpenIMSDK/tools/errs"
|
||||
"github.com/openimsdk/tools/errs"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -164,7 +164,7 @@ More details")
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/OpenIMSDK/tools/log"
|
||||
"github.com/openimsdk/tools/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -226,7 +226,7 @@ More details")
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/OpenIMSDK/tools/log"
|
||||
"github.com/openimsdk/tools/log"
|
||||
"context"
|
||||
)
|
||||
|
||||
@@ -337,7 +337,19 @@ More details")
|
||||
// Suppose an error occurs here
|
||||
err, _ := someFunc()
|
||||
if err != nil {
|
||||
return errs.Wrap(err, "doSomething failed")
|
||||
return errs.WrapMsg(err, "doSomething failed")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
It just works if the package is wrong:
|
||||
|
||||
```go
|
||||
func doSomething() error {
|
||||
// Suppose an error occurs here
|
||||
err, _ := someFunc()
|
||||
if err != nil {
|
||||
return errs.Wrap(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -383,4 +395,113 @@ More details")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
|
||||
### About WrapMsg Use
|
||||
|
||||
```go
|
||||
// "github.com/openimsdk/tools/errs"
|
||||
func WrapMsg(err error, msg string, kv ...any) error {
|
||||
if len(kv) == 0 {
|
||||
if len(msg) == 0 {
|
||||
return errors.WithStack(err)
|
||||
} else {
|
||||
return errors.WithMessage(err, msg)
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if len(msg) > 0 {
|
||||
buf.WriteString(msg)
|
||||
buf.WriteString(" ")
|
||||
}
|
||||
for i := 0; i < len(kv); i += 2 {
|
||||
if i > 0 {
|
||||
buf.WriteString(", ")
|
||||
}
|
||||
buf.WriteString(toString(kv[i]))
|
||||
buf.WriteString("=")
|
||||
buf.WriteString(toString(kv[i+1]))
|
||||
}
|
||||
return errors.WithMessage(err, buf.String())
|
||||
}
|
||||
```
|
||||
|
||||
1. **Function Signature**:
|
||||
- `err error`: The original error object.
|
||||
- `msg string`: The message text to append to the error.
|
||||
- `kv ...any`: A variable number of parameters used to pass key-value pairs. `any` was introduced in Go 1.18 and is equivalent to `interface{}`, meaning any type.
|
||||
|
||||
2. **Logic**:
|
||||
- If there are no key-value pairs (`kv` is empty):
|
||||
- If `msg` is also empty, use `errors.WithStack(err)` to return the original error with the call stack appended.
|
||||
- If `msg` is not empty, use `errors.WithMessage(err, msg)` to append the message text to the original error.
|
||||
- If there are key-value pairs, the function constructs a string containing the message text and all key-value pairs. The key-value pairs are added in the format `"key=value"`, separated by commas. If a message text is provided, it is added first, followed by a space.
|
||||
|
||||
3. **Key-Value Pair Formatting**:
|
||||
- A loop iterates over all the key-value pairs, processing one pair at a time.
|
||||
- The `toString` function (although not provided in the code, we can assume it converts any type to a string) is used to convert both keys and values to strings, and they are added to a `bytes.Buffer` in the format `"key=value"`.
|
||||
|
||||
4. **Result**:
|
||||
- Use `errors.WithMessage(err, buf.String())` to append the constructed message text to the original error, and return this new error object.
|
||||
|
||||
Next, let's demonstrate several ways to use the `WrapMsg` function:
|
||||
|
||||
**Example 1: No Additional Information**
|
||||
|
||||
```go
|
||||
// "github.com/openimsdk/tools/errs"
|
||||
err := errors.New("original error")
|
||||
wrappedErr := errs.WrapMsg(err, "")
|
||||
// wrappedErr will contain the original error and its call stack
|
||||
```
|
||||
|
||||
**Example 2: Message Text Only**
|
||||
|
||||
```go
|
||||
// "github.com/openimsdk/tools/errs"
|
||||
err := errors.New("original error")
|
||||
wrappedErr := errs.WrapMsg(err, "additional error information")
|
||||
// wrappedErr will contain the original error, call stack, and "additional error information"
|
||||
```
|
||||
|
||||
**Example 3: Message Text and Key-Value Pairs**
|
||||
|
||||
```go
|
||||
// "github.com/openimsdk/tools/errs"
|
||||
err := errors.New("original error")
|
||||
wrappedErr := errs.WrapMsg(err, "problem occurred", "code", 404, "url", "webhook://example.com")
|
||||
// wrappedErr will contain the original error, call stack, and "problem occurred code=404, url=http://example.com"
|
||||
```
|
||||
|
||||
**Example 4: Key-Value Pairs Only**
|
||||
|
||||
```go
|
||||
// "github.com/openimsdk/tools/errs"
|
||||
err := errors.New("original error")
|
||||
wrappedErr := errs.WrapMsg(err, "", "user", "john_doe", "action", "login")
|
||||
// wrappedErr will contain the original error, call stack, and "user=john_doe, action=login"
|
||||
```
|
||||
|
||||
> [!TIP] WThese examples demonstrate how the `errs.WrapMsg` function can flexibly handle error messages and context data, helping developers to more effectively track and debug their programs.
|
||||
|
||||
|
||||
### Example 5: Dynamic Key-Value Pairs from Context
|
||||
Suppose we have some runtime context variables, such as a user ID and the type of operation being performed, and we want to include these variables in the error message. This can help with later debugging and identifying the specific environment of the issue.
|
||||
|
||||
```go
|
||||
// Define some context variables
|
||||
userID := "user123"
|
||||
operation := "update profile"
|
||||
errorCode := 500
|
||||
requestURL := "webhook://example.com/updateProfile"
|
||||
|
||||
// Create a new error
|
||||
err := errors.New("original error")
|
||||
|
||||
// Wrap the error, including dynamic key-value pairs from the context
|
||||
wrappedErr := errs.WrapMsg(err, "operation failed", "user", userID, "action", operation, "code", errorCode, "url", requestURL)
|
||||
// wrappedErr will contain the original error, call stack, and "operation failed user=user123, action=update profile, code=500, url=http://example.com/updateProfile"
|
||||
```
|
||||
|
||||
> [!TIP]In this example, the `WrapMsg` function accepts not just a static error message and additional information, but also dynamic key-value pairs generated from the code's execution context, such as the user ID, operation type, error code, and the URL of the request. Including this contextual information in the error message makes it easier for developers to understand and resolve the issue.
|
||||
Reference in New Issue
Block a user