浏览代码

add status.go

dcsunny 4 年之前
父节点
当前提交
afeec156e8
共有 1 个文件被更改,包括 53 次插入0 次删除
  1. 53 0
      http/middleware/status/status.go

+ 53 - 0
http/middleware/status/status.go

@@ -0,0 +1,53 @@
+package status
+
+import (
+	"context"
+
+	"github.com/go-kratos/kratos/v2/errors"
+	"github.com/go-kratos/kratos/v2/middleware"
+	//lint:ignore SA1019 grpc
+)
+
+// HandlerFunc is middleware error handler.
+type HandlerFunc func(error) error
+
+// Option is recovery option.
+type Option func(*options)
+
+type options struct {
+	handler HandlerFunc
+}
+
+// WithHandler with status handler.
+func WithHandler(h HandlerFunc) Option {
+	return func(o *options) {
+		o.handler = h
+	}
+}
+
+// Server is an error middleware.
+func Server(opts ...Option) middleware.Middleware {
+	options := options{
+		handler: errorEncode,
+	}
+	for _, o := range opts {
+		o(&options)
+	}
+	return func(handler middleware.Handler) middleware.Handler {
+		return func(ctx context.Context, req interface{}) (interface{}, error) {
+			reply, err := handler(ctx, req)
+			if err != nil {
+				return nil, options.handler(err)
+			}
+			return reply, nil
+		}
+	}
+}
+
+func errorEncode(err error) error {
+	se := errors.FromError(err)
+	if se == nil {
+		se = errors.New(10400, "", "", err.Error())
+	}
+	return se.GRPCStatus().Err()
+}