Reputation: 15755
I defined some global variables of error code in one packages.Their types are user-defined structs in a package exception. (Go does not support const of structs so I use var)
var (
ErrorCodeSuccess = Error{Code: 0, ErrDetail: "success"} //
)
var (
ACodeDefault = Error{Code: 10000, ErrDetail: "detail1"}
ACodeInValidParams = Error{Code: 10100, ErrDetail: "detail2"}
)
var(
BCodeDefault....// and so on
)
var(
CCodeDefault....// and so on
)
As you can see, a instance of Error define an error code along with its default detail.
But when user really want to specify its details, user can change it like
ACodeDefault.ReNew("more specify details").
This method will return a copy of this Error with a new detail.
Here is my problem, the user specified details may be many.
For example, when user return code 10000, there may be 100 different details in different requests.
But sometimes, I want the default details along with the code to be like 10000-details1 so that I can report to the monitor systems.
So I need a function like mapCodeToDefaultDetails(code int). Then, I hope I can reflect all the variables to build a map(code-> default detail) so that I can implement this method.
is there any ways to achieve this?
Upvotes: 1
Views: 1394
Reputation:
The reflect package does not provide a way to enumerate the variables in a package.
Here's one way to implement the feature: Add a registration function to record the error detail for a code in a map:
var codeDetails = map[int]string{}
func register(e Error) Error {
codeDetails[e.Code] = e.Details
return e
}
Use the registration function when declaring the variables:
var ErrorCodeSuccess = register(Error{Code: 0, ErrDetail: "success"})
Use the map in mapCodeToDefaultDetails:
func mapCodeToDefaultDetails(int code) string {
return codeDetails[code]
}
Upvotes: 1