diff --git a/api.go b/api.go index 0d84f25..2f4c220 100644 --- a/api.go +++ b/api.go @@ -185,6 +185,56 @@ func ErrorHandler(c *gin.Context, errcode int, errmsg string) { 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 type BaseWithEnoOutput = BaseWithErrCodeOutput diff --git a/context.go b/context.go index a8dff65..bc9ccae 100644 --- a/context.go +++ b/context.go @@ -185,6 +185,16 @@ func (c *Context) RESULT_ERROR(eno int, err string) error { 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 { if c.resultentry == "" { c.resultentry = "RESULT_PARAMETER_ERROR"