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

     1  // Copyright © 2023 OpenIM. 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 specialerror
    16  
    17  import "github.com/openimsdk/tools/errs"
    18  
    19  var handlers []func(err error) errs.CodeError
    20  
    21  func AddErrHandler(h func(err error) errs.CodeError) (err error) {
    22  	if h == nil {
    23  		return errs.New("nil handler")
    24  	}
    25  	handlers = append(handlers, h)
    26  	return nil
    27  }
    28  
    29  func AddReplace(target error, codeErr errs.CodeError) error {
    30  	handler := func(err error) errs.CodeError {
    31  		if err == target {
    32  			return codeErr
    33  		}
    34  		return nil
    35  	}
    36  
    37  	if err := AddErrHandler(handler); err != nil {
    38  		return err
    39  	}
    40  
    41  	return nil
    42  }
    43  
    44  func ErrCode(err error) errs.CodeError {
    45  	if codeErr, ok := err.(errs.CodeError); ok {
    46  		return codeErr
    47  	}
    48  	for i := 0; i < len(handlers); i++ {
    49  		if codeErr := handlers[i](err); codeErr != nil {
    50  			return codeErr
    51  		}
    52  	}
    53  	return nil
    54  }