53 lines
1.7 KiB
Go
53 lines
1.7 KiB
Go
|
|
package errors
|
||
|
|
|
||
|
|
import "fmt"
|
||
|
|
|
||
|
|
// AppError 是应用错误结构
|
||
|
|
type AppError struct {
|
||
|
|
Code string // OPS_{CATEGORY}_{CODE}
|
||
|
|
HTTPStatus int
|
||
|
|
Message string
|
||
|
|
Detail map[string]any
|
||
|
|
}
|
||
|
|
|
||
|
|
func (e *AppError) Error() string {
|
||
|
|
return fmt.Sprintf("[%s] %s", e.Code, e.Message)
|
||
|
|
}
|
||
|
|
|
||
|
|
// 预定义错误
|
||
|
|
var (
|
||
|
|
ErrBadRequest = &AppError{Code: "OPS_GEN_4001", HTTPStatus: 400, Message: "请求参数错误"}
|
||
|
|
ErrUnauthorized = &AppError{Code: "OPS_GEN_4002", HTTPStatus: 401, Message: "未授权"}
|
||
|
|
ErrForbidden = &AppError{Code: "OPS_GEN_4003", HTTPStatus: 403, Message: "权限不足"}
|
||
|
|
ErrNotFound = &AppError{Code: "OPS_GEN_4004", HTTPStatus: 404, Message: "资源不存在"}
|
||
|
|
ErrConflict = &AppError{Code: "OPS_GEN_4005", HTTPStatus: 409, Message: "资源冲突"}
|
||
|
|
ErrPayloadTooLarge = &AppError{Code: "OPS_GEN_4006", HTTPStatus: 413, Message: "请求体过大"}
|
||
|
|
ErrInternal = &AppError{Code: "OPS_GEN_5001", HTTPStatus: 500, Message: "内部服务错误"}
|
||
|
|
|
||
|
|
ErrInvalidMetricName = &AppError{Code: "OPS_MET_4001", HTTPStatus: 400, Message: "指标名称无效"}
|
||
|
|
ErrInvalidTimeRange = &AppError{Code: "OPS_MET_4002", HTTPStatus: 400, Message: "时间范围不合法"}
|
||
|
|
)
|
||
|
|
|
||
|
|
// WithDetail 为错误添加详细信息
|
||
|
|
func (e *AppError) WithDetail(detail map[string]any) *AppError {
|
||
|
|
return &AppError{
|
||
|
|
Code: e.Code,
|
||
|
|
HTTPStatus: e.HTTPStatus,
|
||
|
|
Message: e.Message,
|
||
|
|
Detail: detail,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Wrap 包裹原始错误
|
||
|
|
func Wrap(err error, appErr *AppError) *AppError {
|
||
|
|
if err == nil {
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
return &AppError{
|
||
|
|
Code: appErr.Code,
|
||
|
|
HTTPStatus: appErr.HTTPStatus,
|
||
|
|
Message: fmt.Sprintf("%s: %v", appErr.Message, err),
|
||
|
|
Detail: appErr.Detail,
|
||
|
|
}
|
||
|
|
}
|