github.com/cloudwego/kitex@v0.9.0/pkg/remote/trans/nphttp2/codes.go (about)

     1  /*
     2   * Copyright 2021 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package nphttp2
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  
    23  	"github.com/cloudwego/kitex/pkg/kerrors"
    24  	"github.com/cloudwego/kitex/pkg/remote"
    25  	"github.com/cloudwego/kitex/pkg/remote/trans/nphttp2/codes"
    26  	"github.com/cloudwego/kitex/pkg/remote/trans/nphttp2/status"
    27  )
    28  
    29  var kitexErrConvTab = map[error]codes.Code{
    30  	kerrors.ErrInternalException: codes.Internal,
    31  	kerrors.ErrOverlimit:         codes.ResourceExhausted,
    32  	kerrors.ErrRemoteOrNetwork:   codes.Unavailable,
    33  	kerrors.ErrACL:               codes.PermissionDenied,
    34  }
    35  
    36  // convert error to *status.Status
    37  func convertStatus(err error) *status.Status {
    38  	if err == nil {
    39  		return status.New(codes.OK, "")
    40  	}
    41  	// biz error should add biz info which is convenient to be recognized by client side
    42  	var dErr *kerrors.DetailedError
    43  	if errors.As(err, &dErr) && dErr.Is(kerrors.ErrBiz) {
    44  		bizErr := dErr.Unwrap()
    45  		if se, ok := bizErr.(status.Iface); ok {
    46  			gs := se.GRPCStatus()
    47  			gs.AppendMessage(fmt.Sprintf("[%s]", kerrors.ErrBiz.Error())).Err()
    48  			return gs
    49  		}
    50  		if te, ok := bizErr.(*remote.TransError); ok {
    51  			return status.New(codes.Code(te.TypeID()), fmt.Sprintf("%s [%s]", bizErr.Error(), kerrors.ErrBiz.Error()))
    52  		}
    53  		return status.New(codes.Internal, fmt.Sprintf("%s [%s]", bizErr.Error(), kerrors.ErrBiz.Error()))
    54  	}
    55  	// return GRPCStatus() if err is built with status.Error
    56  	if se, ok := err.(interface{ GRPCStatus() *status.Status }); ok {
    57  		return se.GRPCStatus()
    58  	}
    59  	// build status.Status with code if error is remote.TransError
    60  	if te, ok := err.(*remote.TransError); ok {
    61  		return status.New(codes.Code(te.TypeID()), err.Error())
    62  	}
    63  	// covert from kitex error
    64  	if c, ok := kitexErrConvTab[err]; ok {
    65  		return status.New(c, err.Error())
    66  	}
    67  	return status.New(codes.Internal, err.Error())
    68  }