The globalerrors
package provides a convenient way to map custom errors to both HTTP and gRPC status codes. This helps in ensuring consistency in error handling across different service architectures.
To install this package, you can run:
go get -u github.com/thefabric-io/globalerrors
The package offers an HTTPStatus
function which accepts a custom error as an argument and returns the corresponding HTTP status code.
import (
"github.com/thefabric-io/globalerrors"
)
func main() {
err := globalerrors.BadRequest
statusCode := globalerrors.HTTPStatus(err)
// statusCode will be http.StatusBadRequest (400)
}
Similarly, the GRPCStatus
function accepts a custom error and returns the gRPC status code.
import (
"github.com/thefabric-io/globalerrors"
)
func main() {
err := globalerrors.BadRequest
statusCode := globalerrors.GRPCStatus(err)
// statusCode will be codes.InvalidArgument
}
Syntax:
func HTTPStatus(customError error) int
customError
: The custom error for which you want to find the HTTP status code.
Returns: Corresponding HTTP status code as an integer.
Syntax:
func GRPCStatus(customError error) codes.Code
customError
: The custom error for which you want to find the gRPC status code.
Returns: Corresponding gRPC status code.
You can define custom errors that implement the error
interface and use them with the globalerrors
package. Here's an example:
import (
"errors"
"github.com/thefabric-io/globalerrors"
)
func ErrIDIsRequired() error {
return errIDIsRequired{}
}
type errIDIsRequired struct{}
func (e errIDIsRequired) Error() string {
return "id is required"
}
func (e errIDIsRequired) Is(target error) bool {
return errors.Is(target, globalerrors.InternalServerError) || e == target
}
// Usage
func main() {
err := ErrIDIsRequired()
httpStatusCode := globalerrors.HTTPStatus(err)
grpcStatusCode := globalerrors.GRPCStatus(err)
// Since `ErrIDIsRequired` is defined to be equivalent to `globalerrors.InternalServerError`,
// httpStatusCode will be http.StatusInternalServerError (500)
// grpcStatusCode will be codes.Internal
}
In this example, we have defined a custom error ErrIDIsRequired
that implements the error
interface. We have also defined an Is
method to make it compatible with errors.Is
, enabling it to be used with the globalerrors
package.
You can also extend the package to include your custom errors and their corresponding status codes.
- Add your custom error in the
globalErrors
slice.
var globalErrors = []error{
...
YourCustomError,
...
}
- Update
httpStatusCodesMap
and/orgrpcStatusCodesMap
to include the status code mapping for your custom error.
var httpStatusCodesMap = map[error]int{
...
YourCustomError: http.YourStatusCode,
...
}
var grpcStatusCodesMap = map[error]codes.Code{
...
YourCustomError: codes.YourStatusCode,
...
}
We welcome contributions to this project.
This project is licensed under the MIT License - see the LICENSE.md file for details.
For further details and queries, please feel free to reach out.