add feature: c.RESULT_ERRABLE
This commit is contained in:
parent
3a716e5fff
commit
97056563d6
50
api.go
50
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
|
||||
|
||||
|
10
context.go
10
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"
|
||||
|
Loading…
Reference in New Issue
Block a user