grpc-errors
is a middleware providing better error handling to resolve errors easily.
package main
import (
"context"
"net"
"github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/srvc/fail"
"github.com/srvc/grpc-errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
const (
CodeOK uint32 = iota
CodeInvalidArgument
CodeNotFound
CodeYourCustomError
CodeNotWrapped
CodeUnknown
)
var grpcCodeByYourCode = grpcerrors.CodeMap{
CodeOK: codes.OK,
CodeInvalidArgument: codes.InvalidArgument,
CodeNotFound: codes.NotFound,
}
func main() {
lis, err := net.Listen("tcp", "api.example.com:80")
if err != nil {
panic(err)
}
errorHandlers := []grpcerrors.ErrorHandlerFunc{
grpcerrors.WithNotWrappedErrorHandler(func(c context.Context, err error) error {
// WithNotWrappedErrorHandler handles an error not wrapped with `*fail.Error`.
// A handler function should wrap received error with `*fail.Error`.
return fail.Wrap(err, fail.WithCode(CodeNotWrapped))
}),
grpcerrors.WithReportableErrorHandler(func(c context.Context, err *fail.Error) error {
// WithReportableErrorHandler handles an erorr annotated with the reportability.
// You reports to an external service if necessary.
// And you can attach request contexts to error reports.
return err
}),
grpcerrors.WithCodeMap(grpcCodeByYourCode),
}
s := grpc.NewServer(
grpc_middleware.WithStreamServerChain(
grpcerrors.StreamServerInterceptor(errorHandlers...),
),
grpc_middleware.WithUnaryServerChain(
grpcerrors.UnaryServerInterceptor(errorHandlers...),
),
)
// Register server implementations
s.Serve(lis)
}