I have an Go app (web service) which returns errors in json like this:
{errorString: "internal server error"}
It's not ok because "internal server error" is just some programmer error string not usefull for client. The solution is to add error codes:
{errCode: 1, errorString: "internal server error"}
Now, client known that 1 means "internal server error" and can process it as want. For example, show for user message "Internal Server Error" or (in my case) the same in russian lang.
Ok.
So, obviously i need some file where all error constants will be described. For ex. errors.go
const (
ErrNo = iota
// Common Errors
ErrNotFound
ErrInternalServerError
**// More specified errors**
)
The problem is in More specified errors section.
I have 2 ways:
my controller is devided on several files in package server:
clienthandler.go -- for client requests, orderhandler.go -- for orders requests and so on.
specific client errors must be places in clienthandler.go, order errors in orderhandler.go
But how it can be realized?
I know one simple solution: Take some max count of errors for each controller, for example 1000.
clienthandler.go
package server
const (
ErrCheckIdCity = 1000*1 + iota
ErrCheckName
)
that is 1000 errors (from 1000 to 1999) reserved for this file
orderhandler.go
package server
const (
ErrCheckIdCity = 1000*2 + iota
ErrCheckItem
)
that is 1000 errors (from 2000 to 2999) reserved for this file
But disadvantge is that we limit myself by 1000 errors per controller
May be thers is some better way? Or i need just use one global errros.go file ) ?
Place each error where it's originated and export it.
See the link from my comment.
var ErrInvalidParam = fmt.Errorf(“invalid parameter [%s]”, param)
If you want to add an error code, create a new type satisfying the error interface and add the appropriate members like errorCode or related data.
If you want, create a build method as helper, similar as errors.New does