Skip to content

Commit

Permalink
up
Browse files Browse the repository at this point in the history
  • Loading branch information
gqcn committed Nov 24, 2024
1 parent 8b4dc49 commit 449d858
Show file tree
Hide file tree
Showing 22 changed files with 3,491 additions and 856 deletions.
3 changes: 3 additions & 0 deletions .scripts/ai-trans/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@ const (
如果文件顶部的front matter中的description内容中含有单引号,那么将description的值由单引号改为双引号包裹。
不要对顶部的front matter内容使用代码标签包括。
不能删除markdown内容中的图片展示标签内容。
不能翻译链接中的文件路径中的中文名称。
`
)

var (
ignoreFileNames = []string{
"来杯咖啡",
"微服务与框架职责边界",
"Context 业务流程共享变量",
}
)

Expand Down
2 changes: 1 addition & 1 deletion i18n/en/docusaurus-plugin-content-docs/current.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "The label for version current"
},
"sidebar.mainSidebar.category.框架设计": {
"message": "框架设计",
"message": "Design",
"description": "The label for category 框架设计 in sidebar mainSidebar"
},
"sidebar.mainSidebar.category.工程开发设计(🔥重点🔥)": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,44 @@ slug: '/docs/web/panic-handling'
title: 'Exception Handling'
sidebar_position: 8
hide_title: true
keywords: [Exception Handling, GoFrame, WebServer, HTTP Request, Panic Capture, Log Recording, Middleware, Error Stack, Error Handling, gerror]
description: "Strategy for handling HTTP request exceptions using the GoFrame framework. When an exception occurs during a request, GoFrame automatically captures the panic to prevent process crashes and logs it to a file. Developers can customize middleware for exception capturing and processing, and obtain detailed exception stack information to more effectively locate issues. This article also provides several code examples to help readers understand the correct usage of exception handling."
keywords: [Exception Handling, GoFrame, WebServer, HTTP Request, Panic Capture, Logging, Middleware, Error Stack, Error Handling, gerror]
description: "The strategy for handling HTTP request exceptions in the GoFrame framework. When an exception occurs during a request, GoFrame automatically captures the panic to prevent process crashes and logs it to a file. Developers can customize middleware for exception capture and handling, obtaining detailed exception stack information to better pinpoint issues. This article provides multiple code examples to help readers understand the correct usage of exception handling."
---

As this question is frequently asked, we have dedicated this chapter for everyone.
As this question is frequently asked, here is a dedicated section for you.

## Basic Introduction

Currently, most third-party `WebServer` libraries in `Golang` do not have default exception capturing for errors occurring during `HTTP` request processing. At best, errors that occur may not be logged, complicating troubleshooting; at worst, exceptions may cause the process to crash, rendering the service unavailable.
Most third-party `WebServer` libraries for `Golang` do not have default mechanisms to capture exceptions arising during the `HTTP` request handling process. Minor errors may not be recorded in logs, leading to difficulty in troubleshooting, while severe exceptions can cause the process to crash, rendering the service unavailable.

When you choose `goframe`, you're fortunate. As an enterprise-level foundational development framework, by default, any `panic` occurring during execution is automatically captured by the `Server`. The execution flow is immediately halted when a `panic` occurs, but it will never lead to a direct crash of the process.
If you choose `goframe`, you are in luck. As an enterprise-level foundational development framework, `panic` incidents occurring during execution are automatically captured by the `Server` by default. When a `panic` occurs, the current execution flow is immediately halted, but it will never cause a direct process crash.

## Obtaining Exception Errors
## Retrieving Exception Errors

When a `panic` exception occurs during the `HTTP` execution flow, the default action is to log it to the `Server`'s log files. Of course, developers can manually capture errors by registering middleware and then customize the relevant error handling. This operation is also introduced in the middleware chapter's examples, and we'll explain it in detail here.
When a `panic` occurs during the `HTTP` execution process, it is logged to the `Server` log file by default. Developers can also manually capture it by registering middleware and customize related error handling. This operation is also explained in the examples of the middleware section, and we will elaborate on it here.

### Related Methods
### Relevant Methods

We capture exceptions using the `GetError` method in the `Request` object.
Exceptions are captured using the `GetError` method in the `Request` object.
:::tip
Developers cannot use the `recover` method to capture exceptions, as the `goframe` framework's `Server` has already done so. To ensure exceptions won't cause the process to crash by default, they are not rethrown.
Developers cannot capture exceptions using the `recover` method because the `Server` in the `goframe` framework has already done so. To ensure exceptions do not crash the process by default, they are not re-thrown upwards.
:::
```go
// GetError returns the error that occurs during the request procedure.
// It returns nil if there's no error.
func (r *Request) GetError() error
```

This method is mainly used in flow control components, such as post-middleware or `HOOK` functions.
This method is often used in flow control components, such as post-middleware or `HOOK` hook methods.

### Usage Example

Here, we use a global post-middleware to capture exceptions. When an exception occurs, it is captured and written into a specified log file, returning a fixed, friendly message to avoid exposing sensitive error information to the caller.
Here, we use a global post-middleware to capture exceptions. When an exception occurs, it is captured and written to a designated log file, and a fixed friendly message is returned to avoid exposing sensitive error information to the client.
:::tip
Note:
Please note:

- Even if developers have their own logs to capture and record exception errors, the `Server` will still print to its own error log files. Logs outputted via developers' logging interface methods belong to business logs (business-related), while logs managed by the `Server` belong to service logs (similar to `nginx`'s `error.log`).
- As most of the underlying errors in the `goframe` framework contain stack information at the time of error, if you're interested in specific error stack information (such as the call chain, error file path, source line number, etc.), you can use `gerror` to obtain it. For details, please refer to the chapter on [Error Handling - Stack Features](../core-components/error-handling/error-handling-stack-features.md). Errors with stack information will be printed to the `Server`'s `error` log files by default.
- Even if developers capture and log exceptions themselves, the `Server` will still print them to its own error log file. Logs outputted by API methods are business logs (related to the business), while self-managed logs by the `Server` are service logs (similar to `nginx`'s `error.log`).
- Since most low-level errors in the `goframe` framework include stack information of the error, if you are interested in specific stack information (call chain, error file path, source code line number, etc.), you can use `gerror` to retrieve it. For details, please refer to the section [Error Handling - Stack Features](../核心组件/错误处理/错误处理-堆栈特性.md). If the exception includes stack information, it is printed by default to the `Server`'s `error` log file.
:::
```go
package main
Expand All @@ -57,7 +57,7 @@ func MiddlewareErrorHandler(r *ghttp.Request) {
g.Log("exception").Error(err)
// Return a fixed friendly message
r.Response.ClearBuffer()
r.Response.Writeln("The server has gone for a little break, please try again later!")
r.Response.Writeln("The server is having a hiccup. Please try again later!")
}
}

Expand All @@ -74,7 +74,7 @@ func main() {
}
```

After executing, we can try with the `curl` tool:
After execution, let's give it a try with the `curl` tool:

```bash
$ curl -v "http://127.0.0.1:8199/api.v2/user/list"
Expand All @@ -89,14 +89,14 @@ $ curl -v "http://127.0.0.1:8199/api.v2/user/list"
< Content-Length: 52
< Content-Type: text/plain; charset=utf-8
<
The server has gone for a little break, please try again later!
The server is having a hiccup. Please try again later!
```

## Obtaining Exception Stack
## Retrieving Exception Stacks

### Exception Stack Information

When `WebServer` captures exceptions, if the thrown exception does not contain stack content, the `WebServer` will automatically get the stack from the exception point (i.e., the `panic` spot) and create a new error object containing that stack information. Let's look at an example.
When the `WebServer` itself captures an exception, if the thrown exception information does not include stack content, the `WebServer` will automatically capture the stack of the point where the exception occurred (the `panic` location) and create a new error object containing that stack information. Let's look at an example.

```go
package main
Expand Down Expand Up @@ -127,7 +127,7 @@ func main() {
}
```

As you can see, we get stack information from exception errors through `%+v` formatted printing. For specific principles, please refer to the chapter: [Error Handling - Stack Features](../core-components/error-handling/error-handling-stack-features.md). After executing, we can test using the `curl` tool:
You can see that we use the `%+v` formatted print to retrieve the stack information from the exception error; for the specific principle, please refer to the chapter: [Error Handling - Stack Features](../核心组件/错误处理/错误处理-堆栈特性.md). After execution, we will test it with the `curl` tool:

```bash
$ curl "http://127.0.0.1:8199/api.v2/user/list"
Expand Down Expand Up @@ -163,7 +163,7 @@ db error: sql is xxxxxxx

### Error Stack Information

If the thrown exception is an error object via the `gerror` component or an error object that implements the stack printing interface, since the error object already contains detailed stack information, the `WebServer` will directly return that error object without automatically creating a new error object. Let's look at an example.
If the thrown exception is an error object created via the `gerror` component, or an error object implementing the stack print interface, since the error object already contains complete stack information, the `WebServer` will directly return that error object and not automatically create a new error object. Let's look at an example.

```go
package main
Expand Down Expand Up @@ -207,7 +207,7 @@ func main() {
}
```

After executing, we can test using the `curl` tool:
After execution, we will test it with the `curl` tool:

```bash
$ curl "http://127.0.0.1:8199/api.v2/user/list"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ keywords: [OpenAPIv3, GoFrame, API Documentation, Standard Routing, g.Meta, swag
description: "Use the OpenAPIv3 protocol in the GoFrame framework to standardize the generation of API documentation. By embedding the g.Meta metadata structure, you can automatically generate interface information with protocol tags. Additionally, the article shows how to customize extension tags and manually improve the API documentation."
---
:::tip
The `OpenAPIv3` protocol is mainly used in standardized routing. Before reading the introduction to the API documentation protocol, please familiarize yourself with the standardized routing: [Routing Registration - Standard Routing](../routing-management/routing-registration/standard-routing/standard-routing.md)
The `OpenAPIv3` protocol is mainly used in standardized routing. Before reading the introduction to the API documentation protocol, please familiarize yourself with the standardized routing: [Routing Registration - Standard Routing](../路由管理/路由管理-路由注册/路由注册-规范路由/路由注册-规范路由.md)
:::
## I. `OpenAPIv3`

Expand All @@ -17,7 +17,7 @@ For a detailed introduction to the `OpenAPIv3` protocol, please refer to: [https

Interface metadata information can be implemented by embedding the `g.Meta` structure in the input struct and using its attribute tags.

For an introduction to the metadata component, please refer to the section: [Metadata-gmeta](../../component-list/utilities/metadata-gmeta.md)
For an introduction to the metadata component, please refer to the section: [Metadata-gmeta](../../组件列表/实用工具/元数据-gmeta.md)

## III. Common Protocol Tags

Expand Down
Loading

0 comments on commit 449d858

Please sign in to comment.