// CastError returns an error saying that generated code could not properly cast a proto.Message to it's expected type.
351098
func CastError(expectedType proto.Message, actualType proto.Message) error {
	return yarpcerrors.Newf(yarpcerrors.CodeInternal, "expected proto.Message to have type %T but had type %T", expectedType, actualType)
}
1304212
func sendError(rw http.ResponseWriter, code int, err error) {
	resp := errorResponse{Error: errorEntity{Code: code}}
	if err != nil {
		resp.Error.Message = err.Error()
	}
	sendResponse(rw, code, resp)
}
852614
func ServerError(rpcerr error) *Error {
	if rpcerr == nil {
		return nil
	}
	if err, ok := rpcerr.(*Error); ok {
		if err.Code == errInternal.Code && err.Data != nil {
			if err2, ok := err.Data.(*Error); ok {
				// Use alternate error when ReadResponseBody fail on other call.
				return err2
			}
		}
		return err
	}
	keepData := true
	errmsg := rpcerr.Error()
	if s := strings.Index(errmsg, "{"); strings.HasPrefix(errmsg, "reading ") && s != -1 && strings.HasSuffix(errmsg, "}") {
		// ReadResponseBody fail on this call.
		errmsg = errmsg[s:]
		keepData = false
	}
	e := &Error{}
	err := json.Unmarshal([]byte(errmsg), e)
	if err != nil {
		panic(fmt.Sprintf("not a jsonrpc2 error: %s (%#q)", err, rpcerr))
	}
	if e.Code == errInternal.Code && e.Data != nil && !keepData {
		// ReadResponseBody fail on this call.
		e.Data = nil
	}
	return e
}
1298883
func CastValue(ctx sessionctx.Context, val types.Datum, col *model.ColumnInfo) (casted types.Datum, err error) {
	sc := ctx.GetSessionVars().StmtCtx
	casted, err = val.ConvertTo(sc, &col.FieldType)
	// TODO: make sure all truncate errors are handled by ConvertTo.
	err = sc.HandleTruncate(err)
	if err != nil {
		return casted, err
	}

	if col.Tp == mysql.TypeString && !types.IsBinaryStr(&col.FieldType) {
		truncateTrailingSpaces(&casted)
	}

	if ctx.GetSessionVars().SkipUTF8Check {
		return casted, nil
	}
	if !mysql.IsUTF8Charset(col.Charset) {
		return casted, nil
	}
	str := casted.GetString()
	utf8Charset := col.Charset == mysql.UTF8Charset
	doMB4CharCheck := utf8Charset && config.GetGlobalConfig().CheckMb4ValueInUTF8
	for i, w := 0, 0; i < len(str); i += w {
		runeValue, width := utf8.DecodeRuneInString(str[i:])
		if runeValue == utf8.RuneError {
			if strings.HasPrefix(str[i:], string(utf8.RuneError)) {
				w = width
				continue
			}
			casted, err = handleWrongUtf8Value(ctx, col, &casted, str, i)
			break
		} else if width > 3 && doMB4CharCheck {
			// Handle non-BMP characters.
			casted, err = handleWrongUtf8Value(ctx, col, &casted, str, i)
			break
		}
		w = width
	}

	return casted, err
}
582783
func (l *Logger) GenError(format string, v ...interface{}) error {
	s := fmt.Sprintf(format, v...)
	l.base.SetPrefix(l2s[LError])
	l.base.Output(2, s)
	return errors.New(s)
}
719724
func FactoryOf(err error) ErrorFactory {
	errobj := castErrorObject(nil, 1, err)
	if errobj == nil {
		return nil
	}
	return errobj.Factory()
}
58256
func checkErr(err error, handleErr func(string, int)) {
	switch err.(type) {
	case nil:
		return
	case preflightError:
		handleErr(err.Error(), PreFlightExitCode)
	case errorsutil.Aggregate:
		handleErr(err.Error(), ValidationExitCode)

	default:
		handleErr(err.Error(), DefaultErrorExitCode)
	}
}
1153532
func (me *DefaultAdapter) CastExpressionSql(buf *SqlBuilder, cast CastExpression) error {
	buf.WriteString("CAST")
	buf.WriteRune(left_paren_rune)
	if err := me.Literal(buf, cast.Casted()); err != nil {
		return err
	}
	buf.Write(me.AsFragment)
	if err := me.Literal(buf, cast.Type()); err != nil {
		return err
	}
	buf.WriteRune(right_paren_rune)
	return nil
}
243924
func ServeError(rw http.ResponseWriter, r *http.Request, err error) {
	rw.Header().Set("Content-Type", "application/json")
	switch e := err.(type) {
	case *CompositeError:
		er := flattenComposite(e)
		// strips composite errors to first element only
		if len(er.Errors) > 0 {
			ServeError(rw, r, er.Errors[0])
		} else {
			// guard against empty CompositeError (invalid construct)
			ServeError(rw, r, nil)
		}
	case *MethodNotAllowedError:
		rw.Header().Add("Allow", strings.Join(err.(*MethodNotAllowedError).Allowed, ","))
		rw.WriteHeader(asHTTPCode(int(e.Code())))
		if r == nil || r.Method != http.MethodHead {
			_, _ = rw.Write(errorAsJSON(e))
		}
	case Error:
		value := reflect.ValueOf(e)
		if value.Kind() == reflect.Ptr && value.IsNil() {
			rw.WriteHeader(http.StatusInternalServerError)
			_, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
			return
		}
		rw.WriteHeader(asHTTPCode(int(e.Code())))
		if r == nil || r.Method != http.MethodHead {
			_, _ = rw.Write(errorAsJSON(e))
		}
	case nil:
		rw.WriteHeader(http.StatusInternalServerError)
		_, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
	default:
		rw.WriteHeader(http.StatusInternalServerError)
		if r == nil || r.Method != http.MethodHead {
			_, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, err.Error())))
		}
	}
}
215024
func NewEventError(err error) *EventError {
	return &EventError{t: time.Now(), err: err}
}
491146
func copy(t reflect.Value, v reflect.Value) (err error) {
	// if something ends up panicing we need to catch it in a deferred func
	defer func() {
		if r := recover(); r != nil {
			// if we paniced with an error
			if _, ok := r.(error); ok {
				// cast the result to an error object
				err = r.(error)
			} else if _, ok := r.(string); ok {
				// otherwise we could have paniced with a string so wrap it in an error
				err = errors.New(r.(string))
			}
		}
	}()

	// if we are copying from a string result to something else
	if v.Kind() == reflect.String && v.Type() != t.Type() {
		var castVal interface{}
		var casterr error
		vString := v.Interface().(string)

		switch t.Kind() {
		case reflect.Bool:
			castVal, casterr = strconv.ParseBool(vString)
		case reflect.Int:
			castVal, casterr = strconv.Atoi(vString)
		case reflect.Int8:
			var val64 int64
			val64, casterr = strconv.ParseInt(vString, 10, 8)
			if casterr == nil {
				castVal = int8(val64)
			}
		case reflect.Int16:
			var val64 int64
			val64, casterr = strconv.ParseInt(vString, 10, 16)
			if casterr == nil {
				castVal = int16(val64)
			}
		case reflect.Int32:
			var val64 int64
			val64, casterr = strconv.ParseInt(vString, 10, 32)
			if casterr == nil {
				castVal = int32(val64)
			}
		case reflect.Int64:
			castVal, casterr = strconv.ParseInt(vString, 10, 64)
		case reflect.Uint:
			var val64 uint64
			val64, casterr = strconv.ParseUint(vString, 10, 8)
			if casterr == nil {
				castVal = uint(val64)
			}
		case reflect.Uint8:
			var val64 uint64
			val64, casterr = strconv.ParseUint(vString, 10, 8)
			if casterr == nil {
				castVal = uint8(val64)
			}
		case reflect.Uint16:
			var val64 uint64
			val64, casterr = strconv.ParseUint(vString, 10, 16)
			if casterr == nil {
				castVal = uint16(val64)
			}
		case reflect.Uint32:
			var val64 uint64
			val64, casterr = strconv.ParseUint(vString, 10, 32)
			if casterr == nil {
				castVal = uint32(val64)
			}
		case reflect.Uint64:
			castVal, casterr = strconv.ParseUint(vString, 10, 64)
		case reflect.Float32:
			var val64 float64
			val64, casterr = strconv.ParseFloat(vString, 32)
			if casterr == nil {
				castVal = float32(val64)
			}
		case reflect.Float64:
			castVal, casterr = strconv.ParseFloat(vString, 64)
		default:
			return fmt.Errorf("Unable to convert from string to type %s", t.Kind())
		}

		if casterr != nil {
			return casterr
		}

		t.Set(reflect.ValueOf(castVal))
		return
	}

	// if we are copying from one slice or array to another
	if isList(v) && isList(t) {
		// loop over every item in the desired value
		for i := 0; i < v.Len(); i++ {
			// write to the target given its kind
			switch t.Kind() {
			// if its a slice
			case reflect.Slice:
				// an object of the correct type
				obj := reflect.Indirect(reflect.New(t.Type().Elem()))

				// write the appropriate value to the obj and catch any errors
				if err := copy(obj, v.Index(i)); err != nil {
					return err
				}

				// just append the value to the end
				t.Set(reflect.Append(t, obj))
			// otherwise it could be an array
			case reflect.Array:
				// set the index to the appropriate value
				copy(t.Slice(i, i+1).Index(0), v.Index(i))
			}
		}
	} else {
		// set the value to the target
		t.Set(v)
	}

	// we're done
	return
}
1057222
func AddStreamError(reg *descriptor.Registry) error {
	//load internal protos
	any := fileDescriptorProtoForMessage(&any.Any{})
	streamError := fileDescriptorProtoForMessage(&internal.StreamError{})
	if err := reg.Load(&plugin.CodeGeneratorRequest{
		ProtoFile: []*protocdescriptor.FileDescriptorProto{
			any,
			streamError,
		},
	}); err != nil {
		return err
	}
	return nil
}
391258
func HandlerErrorHandler(errorHandler transport.ErrorHandler) HandlerOption {
	return func(h *Handler) { h.errorHandler = errorHandler }
}
842339
func _proto_marshal(obj proto.Message) []byte {
	buf, err := proto.Marshal(obj)
	if err != nil {
		panic(err)
	}
	return buf
}
57989
func (f *RaceFreeFakeWatcher) Error(errValue runtime.Object) {
	f.Lock()
	defer f.Unlock()
	if !f.Stopped {
		select {
		case f.result <- Event{Error, errValue}:
			return
		default:
			panic(fmt.Errorf("channel full"))
		}
	}
}
998103
func (b *Base) ErrorHandler(err error, m message.Composer) {
	b.mutex.RLock()
	defer b.mutex.RUnlock()

	b.errHandler(err, m)
}
1057441
func CastToString(value interface{}) string {
	casted, ok := value.(string)

	if !ok {
		castedStr := fmt.Sprintf("%v", value)
		casted = castedStr
	}

	return casted
}