Skip to content

Commit cd35931

Browse files
committed
improve package gerror/ghttp for error code handling
1 parent 0f6820d commit cd35931

10 files changed

+51
-28
lines changed

errors/gerror/gerror.go

+18-6
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,14 @@ func NewCodef(code int, format string, args ...interface{}) error {
165165

166166
// NewCodeSkip creates and returns an error which has error code and is formatted from given text.
167167
// The parameter <skip> specifies the stack callers skipped amount.
168-
func NewCodeSkip(code, skip int, text string) error {
168+
func NewCodeSkip(code, skip int, text ...string) error {
169+
errText := ""
170+
if len(text) > 0 {
171+
errText = text[0]
172+
}
169173
return &Error{
170174
stack: callers(skip),
171-
text: text,
175+
text: errText,
172176
code: code,
173177
}
174178
}
@@ -185,14 +189,18 @@ func NewCodeSkipf(code, skip int, format string, args ...interface{}) error {
185189

186190
// WrapCode wraps error with code and text.
187191
// It returns nil if given err is nil.
188-
func WrapCode(code int, err error, text string) error {
192+
func WrapCode(code int, err error, text ...string) error {
189193
if err == nil {
190194
return nil
191195
}
196+
errText := ""
197+
if len(text) > 0 {
198+
errText = text[0]
199+
}
192200
return &Error{
193201
error: err,
194202
stack: callers(),
195-
text: text,
203+
text: errText,
196204
code: code,
197205
}
198206
}
@@ -214,14 +222,18 @@ func WrapCodef(code int, err error, format string, args ...interface{}) error {
214222
// WrapCodeSkip wraps error with code and text.
215223
// It returns nil if given err is nil.
216224
// The parameter <skip> specifies the stack callers skipped amount.
217-
func WrapCodeSkip(code, skip int, err error, text string) error {
225+
func WrapCodeSkip(code, skip int, err error, text ...string) error {
218226
if err == nil {
219227
return nil
220228
}
229+
errText := ""
230+
if len(text) > 0 {
231+
errText = text[0]
232+
}
221233
return &Error{
222234
error: err,
223235
stack: callers(skip),
224-
text: text,
236+
text: errText,
225237
code: code,
226238
}
227239
}

errors/gerror/gerror_code.go

+2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const (
2727
CodeServerBusy = 63 // Server is busy, please try again later.
2828
CodeUnknown = 64 // Unknown error.
2929
CodeResourceNotExist = 65 // Resource does not exist.
30+
CodeInvalidRequest = 66 // Invalid request.
3031
CodeBusinessValidationFailed = 300 // Business validation failed.
3132
)
3233

@@ -51,6 +52,7 @@ var (
5152
CodeServerBusy: "Server Is Busy",
5253
CodeUnknown: "Unknown Error",
5354
CodeResourceNotExist: "Resource Not Exist",
55+
CodeInvalidRequest: "Invalid Request",
5456
CodeBusinessValidationFailed: "Business Validation Failed",
5557
}
5658
)

errors/gerror/gerror_error.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func (err *Error) Error() string {
5151
errStr = Message(err.code)
5252
}
5353
if err.error != nil {
54-
if err.text != "" {
54+
if errStr != "" {
5555
errStr += ": "
5656
}
5757
errStr += err.error.Error()

net/ghttp/ghttp_func.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,12 @@ func niceCallFunc(f func()) {
3737
// of the real error point.
3838
if err, ok := exception.(error); ok {
3939
if gerror.Code(err) != gerror.CodeNil {
40-
panic(gerror.Wrap(err, ""))
40+
panic(err)
4141
} else {
42-
panic(gerror.WrapCode(gerror.CodeInternalError, err, ""))
42+
panic(gerror.WrapCodeSkip(gerror.CodeInternalError, 1, err, ""))
4343
}
4444
} else {
45-
panic(gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%v", exception))
45+
panic(gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%+v", exception))
4646
}
4747
}
4848
}

net/ghttp/ghttp_request_param.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"github.com/gogf/gf/encoding/gjson"
1414
"github.com/gogf/gf/encoding/gurl"
1515
"github.com/gogf/gf/encoding/gxml"
16+
"github.com/gogf/gf/errors/gerror"
1617
"github.com/gogf/gf/internal/json"
1718
"github.com/gogf/gf/internal/utils"
1819
"github.com/gogf/gf/text/gregex"
@@ -299,7 +300,7 @@ func (r *Request) parseQuery() {
299300
var err error
300301
r.queryMap, err = gstr.Parse(r.URL.RawQuery)
301302
if err != nil {
302-
panic(err)
303+
panic(gerror.WrapCode(gerror.CodeInvalidParameter, err, ""))
303304
}
304305
}
305306
}
@@ -354,12 +355,12 @@ func (r *Request) parseForm() {
354355
if gstr.Contains(contentType, "multipart/") {
355356
// multipart/form-data, multipart/mixed
356357
if err = r.ParseMultipartForm(r.Server.config.FormParsingMemory); err != nil {
357-
panic(err)
358+
panic(gerror.WrapCode(gerror.CodeInvalidRequest, err, ""))
358359
}
359360
} else if gstr.Contains(contentType, "form") {
360361
// application/x-www-form-urlencoded
361362
if err = r.Request.ParseForm(); err != nil {
362-
panic(err)
363+
panic(gerror.WrapCode(gerror.CodeInvalidRequest, err, ""))
363364
}
364365
}
365366
if len(r.PostForm) > 0 {
@@ -402,7 +403,7 @@ func (r *Request) parseForm() {
402403
}
403404
if params != "" {
404405
if r.formMap, err = gstr.Parse(params); err != nil {
405-
panic(err)
406+
panic(gerror.WrapCode(gerror.CodeInvalidParameter, err, ""))
406407
}
407408
}
408409
}

net/ghttp/ghttp_request_param_page.go

+13-6
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,15 @@ import (
1717
// NOTE THAT the page parameter name from client is constantly defined as gpage.DefaultPageName
1818
// for simplification and convenience.
1919
func (r *Request) GetPage(totalSize, pageSize int) *gpage.Page {
20-
// It must has Router object attribute.
20+
// It must have Router object attribute.
2121
if r.Router == nil {
2222
panic("Router object not found")
2323
}
24-
url := *r.URL
25-
urlTemplate := url.Path
26-
uriHasPageName := false
24+
var (
25+
url = *r.URL
26+
urlTemplate = url.Path
27+
uriHasPageName = false
28+
)
2729
// Check the page variable in the URI.
2830
if len(r.Router.RegNames) > 0 {
2931
for _, name := range r.Router.RegNames {
@@ -39,12 +41,17 @@ func (r *Request) GetPage(totalSize, pageSize int) *gpage.Page {
3941
for i, name := range r.Router.RegNames {
4042
rule := fmt.Sprintf(`[:\*]%s|\{%s\}`, name, name)
4143
if name == gpage.DefaultPageName {
42-
urlTemplate, _ = gregex.ReplaceString(rule, gpage.DefaultPagePlaceHolder, urlTemplate)
44+
urlTemplate, err = gregex.ReplaceString(rule, gpage.DefaultPagePlaceHolder, urlTemplate)
4345
} else {
44-
urlTemplate, _ = gregex.ReplaceString(rule, match[i+1], urlTemplate)
46+
urlTemplate, err = gregex.ReplaceString(rule, match[i+1], urlTemplate)
47+
}
48+
if err != nil {
49+
panic(err)
4550
}
4651
}
4752
}
53+
} else {
54+
panic(err)
4855
}
4956
}
5057
}

net/ghttp/ghttp_server.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ func GetServer(name ...interface{}) *Server {
107107
}
108108
// Initialize the server using default configurations.
109109
if err := s.SetConfig(NewConfig()); err != nil {
110-
panic(err)
110+
panic(gerror.WrapCode(gerror.CodeInvalidConfiguration, err, ""))
111111
}
112112
// Record the server to internal server mapping by name.
113113
serverMapping.Set(serverName, s)

net/ghttp/ghttp_server_handler.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
6868
request.Response.WriteStatus(http.StatusInternalServerError)
6969
if err, ok := exception.(error); ok {
7070
if code := gerror.Code(err); code != gerror.CodeNil {
71-
s.handleErrorLog(gerror.Wrap(err, ""), request)
71+
s.handleErrorLog(err, request)
7272
} else {
73-
s.handleErrorLog(gerror.WrapCode(gerror.CodeInternalError, err, ""), request)
73+
s.handleErrorLog(gerror.WrapCodeSkip(gerror.CodeInternalError, 1, err, ""), request)
7474
}
7575
} else {
76-
s.handleErrorLog(gerror.NewCodef(gerror.CodeInternalError, "%v", exception), request)
76+
s.handleErrorLog(gerror.NewCodeSkipf(gerror.CodeInternalError, 1, "%+v", exception), request)
7777
}
7878
}
7979
}

net/ghttp/ghttp_server_router_serve.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ package ghttp
88

99
import (
1010
"fmt"
11+
"github.com/gogf/gf/errors/gerror"
1112
"github.com/gogf/gf/internal/json"
1213
"strings"
1314

@@ -175,8 +176,8 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
175176
parsedItemList.PushBack(parsedItem)
176177

177178
// The middleware is inserted before the serving handler.
178-
// If there're multiple middleware, they're inserted into the result list by their registering order.
179-
// The middleware are also executed by their registered order.
179+
// If there are multiple middleware, they're inserted into the result list by their registering order.
180+
// The middleware is also executed by their registered order.
180181
case handlerTypeMiddleware:
181182
if lastMiddlewareElem == nil {
182183
lastMiddlewareElem = parsedItemList.PushFront(parsedItem)
@@ -190,7 +191,7 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
190191
parsedItemList.PushBack(parsedItem)
191192

192193
default:
193-
panic(fmt.Sprintf(`invalid handler type %d`, item.Type))
194+
panic(gerror.NewCodef(gerror.CodeInternalError, `invalid handler type %d`, item.Type))
194195
}
195196
}
196197
}

net/ghttp/ghttp_unit_config_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ func Test_ClientMaxBodySize_File(t *testing.T) {
152152
defer gfile.Remove(path)
153153
t.Assert(
154154
gstr.Trim(c.PostContent("/", "name=john&file=@file:"+path)),
155-
"http: request body too large",
155+
"Invalid Request: http: request body too large",
156156
)
157157
})
158158
}

0 commit comments

Comments
 (0)