Error Handle
Error
The Error struct in Hertz:
Err
is standard error, Type
is the type of error, Meta
is the metadata.
Error Type
In order to handle errors more efficiently, Hertz has predefined the following error types:
It is recommended to define the corresponding errors according to the error type.
Custom Error
Using the following functions:
Relevant functions
signature | description |
---|---|
SetType(flags ErrorType) *Error | set the ErrorType to the given flags |
Error() string | implement the error interface |
Unwrap() error | throw an error |
SetMeta(data interface{}) *Error | set the Meta to the given data |
IsType(flags ErrorType) bool | determine whether the ErrorType matches the given flags |
JSON() interface{} | convert the error to a json object |
ErrorChain
In addition to the conventions for error definition, the framework also provides ErrorChain capability. As the name implies, it is easy for the business to bind all errors encountered on a request processing to the error chain, which can facilitate the subsequent (usually in the middleware) unified processing of all errors.
Relevant functions
signature | description |
---|---|
String() string | return a human-readable text for displaying all errors |
Errors() []string | convert the ErrorChain to an array of standard errors |
ByType(typ ErrorType) ErrorChain | return the corresponding sub-ErrorChain for the given error type |
Last() *Error | return the last error |
JSON() interface{} | convert all errors to a json object |
How To Use
The corresponding API is: RequestContext.Error(err)
, and calling this API will tie the err to the corresponding request context.
Method to get all the errors that have been bound by the request context: RequestContext.Errors
.