github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/errors/reflect.go (about)

     1  // Copyright 2022 PingCAP, Inc.
     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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package errors
    15  
    16  import (
    17  	"regexp"
    18  	"strconv"
    19  
    20  	"github.com/pingcap/errors"
    21  	"github.com/pingcap/tiflow/dm/pkg/terror"
    22  )
    23  
    24  const (
    25  	dmErrBaseFormat = "\\[code=([0-9]+):class=[a-zA-Z-]+:scope=[a-zA-Z-]+:level=[a-zA-Z]+\\](.*)"
    26  )
    27  
    28  var dmErrRegexp = regexp.MustCompile(dmErrBaseFormat)
    29  
    30  // ToDMError tries best to construct a DM terror from an error object
    31  // - If err wraps a DM standard error, return it directly.
    32  // - If not, checks whether error message matches DM standard error format
    33  //   - If it does, construct a DM terror from the error code and message.
    34  //   - Otherwise returns the original error
    35  func ToDMError(err error) error {
    36  	if _, ok := errors.Cause(err).(*terror.Error); ok {
    37  		return err
    38  	}
    39  
    40  	subMatch := dmErrRegexp.FindStringSubmatch(err.Error())
    41  	if len(subMatch) > 2 {
    42  		code, _ := strconv.Atoi(subMatch[1])
    43  		if baseError, ok := terror.ErrorFromCode(terror.ErrCode(code)); ok {
    44  			return baseError.Generatef(subMatch[2])
    45  		}
    46  	}
    47  
    48  	return err
    49  }