跳到主要内容

自定义错误码

server/http_codec.go


// 自定义错误响应编码器, 统一错误的响应结构
func customEncodeErrorFunc(w http.ResponseWriter, r *http.Request, err error) {
if err == nil {
return
}

// 判断是否是gRPC的错误类型
var response *httpResponse
if gs, ok := status.FromError(err); ok {
response = &httpResponse{
Code: krstatus.FromGRPCCode(gs.Code()),
Msg: gs.Message(),
}
} else {
response = &httpResponse{
Code: http.StatusInternalServerError,
Msg: "内部错误",
}
}

codec, _ := krhttp.CodecForRequest(r, "Accept")
// 将自定义的错误结构体进行解码
body, err := codec.Marshal(response)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", fmt.Sprintf("application/%s", codec.Name()))
// 写入错误码
w.WriteHeader(response.Code)
_, _ = w.Write(body)
}

server/http.go

opts = append(opts,http.ErrorEncoder(customEncodeErrorFunc))