[feat] 优化错误提示

This commit is contained in:
2023-08-30 14:55:01 +08:00
parent afa9cba84b
commit 8f0e1f605d
2 changed files with 13 additions and 55 deletions

View File

@@ -2,9 +2,9 @@ package support
import (
"encoding/json"
"fmt"
"net/http"
"os"
"runtime"
"strings"
"git.fsdpf.net/go/contracts"
@@ -125,51 +125,13 @@ func NewMsgResponse(msg string, code int) contracts.HttpResponse {
return &MsgResponse{msg: msg, code: code}
}
func NewErrResponse(p ...any) contracts.HttpResponse {
code := contracts.InternalServerError.Code
msg := contracts.InternalServerError.Error()
data := any(nil)
for i := 0; i < len(p); i++ {
switch v := p[i].(type) {
case error:
msg = v.Error()
case string:
msg = v
case int:
code = v
case contracts.Errno:
msg = v.Error()
code = v.Code
case *contracts.Errno:
msg = v.Error()
code = v.Code
default:
data = v
}
}
stackBuf := make([]byte, 1024)
n := runtime.Stack(stackBuf[:], false)
b, _ := json.Marshal(struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data,omitempty"`
Stack string `json:"stack"`
}{
Code: code,
Msg: msg,
Data: data,
Stack: string(stackBuf[:n]),
})
return NewJsonResponse(b)
func NewErrResponse(err *contracts.Err) contracts.HttpResponse {
return NewJsonResponse([]byte(fmt.Sprintf(`{"code": %d, "msg": %q, "errord": %q}`, err.Code, err.Msg, err.Errord)))
}
func HttpResponse(data any) contracts.HttpResponse {
var err error = contracts.InternalServerError
var err error
// fmt.Printf("%#v \n", data)
switch v := data.(type) {
case contracts.HttpResponse:
return v
@@ -177,6 +139,10 @@ func HttpResponse(data any) contracts.HttpResponse {
return NewMsgResponse(v.Error(), v.Code)
case *contracts.Errno:
return NewMsgResponse(v.Error(), v.Code)
case contracts.Err:
return NewErrResponse(&v)
case *contracts.Err:
return NewErrResponse(v)
case error:
err = v
case []byte:
@@ -201,5 +167,5 @@ func HttpResponse(data any) contracts.HttpResponse {
}
}
return NewMsgResponse(err.Error(), contracts.InternalServerError.Code)
return NewErrResponse(contracts.NewErr(contracts.InternalServerError, err))
}