[feat] 优化错误提示

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

View File

@ -1,10 +1,5 @@
package contracts
import (
"fmt"
"runtime"
)
// 定义错误码
type Errno struct {
Code int `json:"code"`
@ -23,7 +18,7 @@ type Err struct {
}
func (err *Err) Error() string {
return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Msg, err.Errord)
return err.Errord
}
// 错误码设计
@ -95,12 +90,9 @@ var (
// 使用 错误码 和 error 创建新的 错误
func NewErr(errno *Errno, err error) *Err {
stackBuf := make([]byte, 1024)
n := runtime.Stack(stackBuf[:], false)
return &Err{
Code: errno.Code,
Msg: err.Error(),
Errord: string(stackBuf[:n]),
Msg: errno.Error(),
Errord: err.Error(),
}
}

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))
}