Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the skills of graceful handling of Error in Go applications

2025-03-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the skills of elegant handling of Error in Go applications. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

User-defined type

We will rewrite the error type included in the Go, starting with a custom error type that will be recognized as the error type in the program. Therefore, we introduce a new custom Error type that encapsulates error for Go.

Type GoError struct {error} context data

When we say error is a value in Go, it is a string value-any type that implements the Error () string function can be considered an error type. Treating string values as error complicates cross-layer error processing, so dealing with error string information is not the right approach. So we can decouple the string from the error code:

Type GoError struct {error Code string}

Now the processing of error will be based on the error code Code field rather than the string. Let's further decouple the error string through the context data, where i18n packages can be used for internationalization.

Type GoError struct {error Code string Data map[string] interface {}}

The Data contains the context data used to construct the error string. Error strings can be templated by data:

/ / i18N def

"InvalidParamValue": "Invalid parameter value'{{actual}}', expected'{{actual}}''for' {{.name}}'"

In the i18n definition file, the error code Code will be mapped to a templated error string built using Data.

Cause (Causes)

Error can occur at any layer, and it is necessary to provide each layer with the option to process the error and further wrap the error with additional context information without losing the original error value. The GoError structure can be further encapsulated with Causes to hold the entire error stack.

Type GoError struct {error Code string Data map[string] interface {} Causes [] error}

If multiple error data must be saved, causes is an array type and set to the basic error type to include a third-party error for that reason in the program.

Component (Component)

The tag layer components will help identify the layer at which the error occurs and avoid unnecessary error wrap. For example, if the error component of type service occurs at the service layer, wrap error may not be required. Checking component information will help prevent exposure to error that users should not notify, such as database error:

Type GoError struct {error Code string Data map [string] interface {} Causes [] error Component ErrComponent} type ErrComponent stringconst (ErrService ErrComponent = "service" ErrRepo ErrComponent = "repository" ErrLib ErrComponent = "library") response type (ResponseType)

Add an error response type so that you can support error classification so that you can know what error type is. For example, error can be classified by response type (such as NotFound), and error such as DbRecordNotFound, ResourceNotFound, UserNotFound, and so on, can be classified as NotFound error. This is useful in multi-tier application development and is an optional encapsulation:

Type GoError struct {error Code string Data map [string] interface {} Causes [] error Component ErrComponent ResponseType ResponseErrType} type ResponseErrType stringconst (BadRequest ResponseErrType = "BadRequest" Forbidden ResponseErrType = "Forbidden" NotFound ResponseErrType = "NotFound" AlreadyExists ResponseErrType = "AlreadyExists") retry

In a few cases, the presence of an error will retry. The retry field can determine whether to retry error by setting the Retryable flag:

Type GoError struct {error Code string Message string Data map [string] interface {} Causes [] error Component ErrComponent ResponseType ResponseErrType Retryable bool} GoError interface

You can simplify error checking by defining an explicit error interface with an GoError implementation:

Package goerrtype Error interface {error Code () string Message () string Cause () error Causes () [] error Data () map [string] interface {} String () string ResponseErrType () ResponseErrType SetResponseType (r ResponseErrType) Error Component () ErrComponent SetComponent (c ErrComponent) Error Retryable () bool SetRetryable () Error} Abstract error

With the above encapsulation, it is more important to abstract the error, store these wrappers in the same place, and provide the reusability of the error function

Func ResourceNotFound (id, kind string, cause error) GoError {data: = map [string] interface {} {"kind": kind, "id": id} return GoError {Code: "ResourceNotFound", Data: data, Causes: [] error {cause}, Component: ErrService, ResponseType: NotFound, Retryable: false,}}

This error function abstracts the error of ResourceNotFound, which developers can use to return error objects instead of creating new objects one at a time:

/ / UserServiceuser, err: = u.repo.FindUser (ctx, userId) if err! = nil {if err.ResponseType = = NotFound {return ResourceNotFound (userUid, "User", err)} return err} this is the end of this article on "what are the elegant Error handling skills in Go applications". I hope the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good. Please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report