add feature: c.RESULT_ERRABLE

This commit is contained in:
bryan 2025-09-04 01:06:41 +08:00
parent 3a716e5fff
commit 97056563d6
2 changed files with 60 additions and 0 deletions

50
api.go
View File

@ -185,6 +185,56 @@ func ErrorHandler(c *gin.Context, errcode int, errmsg string) {
handler(c) handler(c)
} }
type Error struct {
err error
Code int
Message string
}
func (err Error) MarshalJSON() ([]byte, error) {
var o = map[string]any{
apicfg.OutputErrCodeName: err.Code,
apicfg.OutputErrMessageName: err.Message,
}
return json.Marshal(o)
}
func (err Error) Error() string {
return fmt.Sprintf("%d:%s", err.Code, err.Message)
}
func (err Error) Unwrap() error {
return err.err
}
// Errable error | string
type Errable any
// NewError create a new Error for c.RESULT_ERRABLE,
// the type of err must be error or string.
func NewError(code int, err Errable) Error {
newErr := Error{
Code: code,
}
switch v := any(err).(type) {
case error:
newErr.err = v
newErr.Message = v.Error()
case string:
newErr.err = nil
newErr.Message = v
default:
panic("unreachable code")
}
return newErr
}
// NewError create a new Error for c.RESULT_ERRABLE,
func NewErrorf(code int, format string, args ...any) Error {
err := fmt.Errorf(format, args...)
return NewError(code, err)
}
// deprecated, use "BaseWithErrCodeOutput + api.Init" instead // deprecated, use "BaseWithErrCodeOutput + api.Init" instead
type BaseWithEnoOutput = BaseWithErrCodeOutput type BaseWithEnoOutput = BaseWithErrCodeOutput

View File

@ -185,6 +185,16 @@ func (c *Context) RESULT_ERROR(eno int, err string) error {
return c.RESULT(result) return c.RESULT(result)
} }
func (c *Context) RESULT_ERRABLE(err Error) error {
if c.resultentry == "" {
c.resultentry = "RESULT_ERROR"
}
result := BaseWithErrCodeOutput{err.Code, err.Message}
c.errcode = err.Code
return c.RESULT(result)
}
func (c *Context) RESULT_PARAMETER_ERROR(err string) error { func (c *Context) RESULT_PARAMETER_ERROR(err string) error {
if c.resultentry == "" { if c.resultentry == "" {
c.resultentry = "RESULT_PARAMETER_ERROR" c.resultentry = "RESULT_PARAMETER_ERROR"