parent
e2f234c17e
commit
dd36810af7
@ -0,0 +1,8 @@
|
||||
module git.blauwelle.com/go/crate/cdata
|
||||
|
||||
go 1.21.3
|
||||
|
||||
require (
|
||||
git.blauwelle.com/go/crate/cerrors v0.1.0
|
||||
git.blauwelle.com/go/crate/runtimehelper v0.2.0
|
||||
)
|
@ -0,0 +1,6 @@
|
||||
git.blauwelle.com/go/crate/cerrors v0.0.0-20240507062518-e2f234c17eb2 h1:h3WnMe7tQNbh6WARbixrf8wTUrWCDNc3F6ikb1HQhj4=
|
||||
git.blauwelle.com/go/crate/cerrors v0.0.0-20240507062518-e2f234c17eb2/go.mod h1:vIWWWVAEwattbg1eVOUjnz5dEG7q7v/Ve0oR1HFsblM=
|
||||
git.blauwelle.com/go/crate/cerrors v0.1.0 h1:+9TdG54+AUG1NmUgrEPsAPY8n8RIUAQy9qx4drU9RtE=
|
||||
git.blauwelle.com/go/crate/cerrors v0.1.0/go.mod h1:vIWWWVAEwattbg1eVOUjnz5dEG7q7v/Ve0oR1HFsblM=
|
||||
git.blauwelle.com/go/crate/runtimehelper v0.2.0 h1:W19wipPCyFSGHOWzqtfouNJu7MDeJobP+iRM4bPiJpM=
|
||||
git.blauwelle.com/go/crate/runtimehelper v0.2.0/go.mod h1:yVMA0GkO9AS7iuPmalHKeWyv9en0JWj25rY1vpTuHhk=
|
@ -0,0 +1,64 @@
|
||||
package cdata
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.blauwelle.com/go/crate/cerrors"
|
||||
"git.blauwelle.com/go/crate/runtimehelper"
|
||||
)
|
||||
|
||||
const maximumFrames = 16
|
||||
|
||||
type Response[T any] struct {
|
||||
Data T `json:"data,omitempty"`
|
||||
Code cerrors.Code `json:"code"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Debug string `json:"debug,omitempty"`
|
||||
Traceback []runtimehelper.Frame `json:"traceback,omitempty"`
|
||||
}
|
||||
|
||||
type PageData[T any] struct {
|
||||
List []T `json:"list"`
|
||||
PageIndex int `json:"pageIndex"` // >=1
|
||||
PageSize int `json:"pageSize"` // >=1
|
||||
Total int `json:"total"` // maybe 0
|
||||
}
|
||||
|
||||
func NewOkResponse[T any](data T) Response[T] {
|
||||
return Response[T]{
|
||||
Code: cerrors.CodeOK,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func NewResponseFromError(err error) Response[struct{}] {
|
||||
e := &cerrors.Error{}
|
||||
if !errors.As(err, &e) {
|
||||
response := Response[struct{}]{
|
||||
Code: cerrors.CodeUnknown,
|
||||
Message: "未知错误",
|
||||
}
|
||||
if cerrors.FlagDebug {
|
||||
response.Debug = err.Error()
|
||||
response.Traceback = runtimehelper.Stack(1, maximumFrames)
|
||||
}
|
||||
return response
|
||||
}
|
||||
return Response[struct{}]{
|
||||
Code: e.Code,
|
||||
Message: e.Message,
|
||||
Debug: e.Debug,
|
||||
Traceback: e.Traceback,
|
||||
}
|
||||
}
|
||||
|
||||
func NewErrorResponse(code cerrors.Code, message string) Response[struct{}] {
|
||||
response := Response[struct{}]{
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
if cerrors.FlagDebug {
|
||||
response.Traceback = runtimehelper.Stack(1, maximumFrames)
|
||||
}
|
||||
return response
|
||||
}
|
Loading…
Reference in New Issue