go-grpc-gateway:如何链接多个http错误

问题描述 投票:0回答:1

在 grpc-gateway 中我们如何链接多个错误处理程序

例如看起来像这样

import "github.com/grpc-ecosystem/grpc-gateway/runtime"

    //first error handler
    var runTimeError1 = func(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
            
            stat, ok := status.FromError(err)
            fmt.Println("body")
            if !ok || len(stat.Details()) != 1 {
                fmt.Println("in unknown error")
            }
            statusCode := runtime.HTTPStatusFromCode(stat.Code())
            fmt.Println("code", statusCode)
        }
    // another error handler
    var runTimeError2 = func(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
            
            stat, ok := status.FromError(err)
            fmt.Println("body")
            if !ok || len(stat.Details()) != 1 {
                fmt.Println("in unknown error")
            }
            statusCode := runtime.HTTPStatusFromCode(stat.Code())
            fmt.Println("code", statusCode)
        }
    
    runtime.HTTPError = runTimeError1

我需要的是将两个错误组合成这样的链

runtime.HTTPError = [runTimeError1,runTimeError2]

以上的实现可以在grpc-gateway中实现吗?

go protocol-buffers go-grpc-middleware
1个回答
0
投票

您可以将所有处理程序合并为一个处理程序。这是一个稍微过度设计的例子:

type ErrHandler func(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error)
type ChainedErrHandler []ErrHandler

func (c ChainedErrHandler) Merge() ErrHandler {
    return func(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
        for _, handler := range c {
            handler(ctx, mux, marshaler, w, r, err)
        }
    }
}

func main() {
    var runTimeError1 ErrHandler = func(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
        fmt.Println("handling error", err, "in handler 1")
    }
    var runTimeError2 ErrHandler = func(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
        fmt.Println("handling error", err, "in handler 2")
    }
    chainedHandlers := ChainedErrHandler{runTimeError1, runTimeError2}.Merge()
    runtime.HTTPError = chainedHandlers
}
© www.soinside.com 2019 - 2024. All rights reserved.