throwError.go 1.5 KB
package lib

import "strings"

const (
	INTERNAL_SERVER_ERROR = iota + 1
	BAD_GATEWAY_ERROR
	TRANSACTION_ERROR
	ARG_ERROR
	RES_NO_FIND_ERROR
	BUSINESS_ERROR
)

type ServiceError struct {
	Prefix  string
	Code    int
	Message string
}

func (serviceError ServiceError) Error() string {
	return serviceError.Message
}

func ThrowError(serviceErrorNo int, attachMessages ...string) error {
	switch serviceErrorNo {
	case INTERNAL_SERVER_ERROR:
		return ServiceError{
			Prefix:  "内部服务出错:",
			Code:    INTERNAL_SERVER_ERROR,
			Message: strings.Join(attachMessages, ""),
		}
	case BAD_GATEWAY_ERROR:
		return ServiceError{
			Prefix:  "服务网关错误:",
			Code:    BAD_GATEWAY_ERROR,
			Message: strings.Join(attachMessages, ""),
		}
	case TRANSACTION_ERROR:
		return ServiceError{
			Prefix:  "事务处理错误:",
			Code:    TRANSACTION_ERROR,
			Message: strings.Join(attachMessages, ""),
		}
	case ARG_ERROR:
		return ServiceError{
			Prefix:  "参数认证错误:",
			Code:    ARG_ERROR,
			Message: strings.Join(attachMessages, ""),
		}
	case RES_NO_FIND_ERROR:
		return ServiceError{
			Prefix:  "找不到相关资源:",
			Code:    RES_NO_FIND_ERROR,
			Message: strings.Join(attachMessages, ""),
		}
	case BUSINESS_ERROR:
		return ServiceError{
			Prefix:  "业务逻辑错误:",
			Code:    BUSINESS_ERROR,
			Message: strings.Join(attachMessages, ""),
		}
	default:
		return ServiceError{
			Prefix:  "未定义错误:",
			Code:    500,
			Message: strings.Join(attachMessages, ""),
		}
	}
}