github.com/cloudwego/kitex@v0.9.0/pkg/remote/codec/protobuf/pberror.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 protobuf
    18  
    19  import (
    20  	"google.golang.org/protobuf/proto"
    21  )
    22  
    23  type PBError interface {
    24  	error
    25  	TypeID() int32
    26  	Marshal(out []byte) ([]byte, error)
    27  	Unmarshal(in []byte) error
    28  }
    29  
    30  type pbError struct {
    31  	errProto *ErrorProto
    32  }
    33  
    34  func NewPbError(typeID int32, message string) PBError {
    35  	err := &ErrorProto{TypeID: typeID, Message: message}
    36  	return &pbError{errProto: err}
    37  }
    38  
    39  func (p pbError) Error() string {
    40  	return p.errProto.Message
    41  }
    42  
    43  func (p *pbError) IsSetError() bool {
    44  	return p.errProto != nil
    45  }
    46  
    47  func (p *pbError) Marshal(out []byte) ([]byte, error) {
    48  	if !p.IsSetError() {
    49  		return out, nil
    50  	}
    51  	return proto.Marshal(p.errProto)
    52  }
    53  
    54  func (p *pbError) Unmarshal(in []byte) error {
    55  	err := new(ErrorProto)
    56  	if err := proto.Unmarshal(in, err); err != nil {
    57  		return err
    58  	}
    59  	p.errProto = err
    60  	return nil
    61  }
    62  
    63  func (p *pbError) TypeID() int32 {
    64  	return p.errProto.TypeID
    65  }