github.com/openimsdk/tools@v0.0.49/errs/error.go (about)

     1  // Copyright © 2024 OpenIM open source community. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package errs
    16  
    17  import (
    18  	"bytes"
    19  	"fmt"
    20  )
    21  
    22  type Error interface {
    23  	Is(err error) bool
    24  	Wrap() error
    25  	WrapMsg(msg string, kv ...any) error
    26  	error
    27  }
    28  
    29  func New(s string, kv ...any) Error {
    30  	return &errorString{
    31  		s: toString(s, kv),
    32  	}
    33  }
    34  
    35  type errorString struct {
    36  	s string
    37  }
    38  
    39  func (e *errorString) Is(err error) bool {
    40  	if err == nil {
    41  		return false
    42  	}
    43  	t, ok := err.(*errorString)
    44  	return ok && e.s == t.s
    45  }
    46  
    47  func (e *errorString) Error() string {
    48  	return e.s
    49  }
    50  
    51  func (e *errorString) Wrap() error {
    52  	return Wrap(e)
    53  }
    54  
    55  func (e *errorString) WrapMsg(msg string, kv ...any) error {
    56  	return WrapMsg(e, msg, kv...)
    57  }
    58  
    59  func toString(s string, kv []any) string {
    60  	if len(kv) == 0 {
    61  		return s
    62  	} else {
    63  		var buf bytes.Buffer
    64  		buf.WriteString(s)
    65  
    66  		for i := 0; i < len(kv); i += 2 {
    67  			if buf.Len() > 0 {
    68  				buf.WriteString(", ")
    69  			}
    70  
    71  			key := fmt.Sprintf("%v", kv[i])
    72  			buf.WriteString(key)
    73  			buf.WriteString("=")
    74  
    75  			if i+1 < len(kv) {
    76  				value := fmt.Sprintf("%v", kv[i+1])
    77  				buf.WriteString(value)
    78  			} else {
    79  				buf.WriteString("MISSING")
    80  			}
    81  		}
    82  		return buf.String()
    83  	}
    84  }