Update error handler

pull/448/head
Fenny 2020-06-06 20:49:02 +02:00
parent 5739c24f0d
commit a8f8f30b5d
3 changed files with 15 additions and 15 deletions

24
app.go
View File

@ -54,14 +54,14 @@ type App struct {
type Settings struct {
// ErrorHandler is executed when you pass an error in the Next(err) method
// This function is also executed when middleware.Recover() catches a panic
// Default: func(ctx *Ctx) {
// Default: func(ctx *Ctx, err error) {
// code := StatusInternalServerError
// if e, ok := ctx.Error().(*Error); ok {
// if e, ok := err.(*Error); ok {
// code = e.Code
// }
// ctx.Status(code).SendString(ctx.Error().Error())
// ctx.Status(code).SendString(err.Error())
// }
ErrorHandler Handler
ErrorHandler func(*Ctx, error)
// Enables the "Server: value" HTTP header.
// Default: ""
@ -220,12 +220,12 @@ func New(settings ...*Settings) *App {
Prefork: utils.GetArgument("-prefork"),
BodyLimit: 4 * 1024 * 1024,
Concurrency: 256 * 1024,
ErrorHandler: func(ctx *Ctx) {
ErrorHandler: func(ctx *Ctx, err error) {
code := StatusInternalServerError
if e, ok := ctx.Error().(*Error); ok {
if e, ok := err.(*Error); ok {
code = e.Code
}
ctx.Status(code).SendString(ctx.Error().Error())
ctx.Status(code).SendString(err.Error())
},
},
}
@ -247,14 +247,14 @@ func New(settings ...*Settings) *App {
getBytes = getBytesImmutable
getString = getStringImmutable
}
// Set default error handler
// Set default error
if app.Settings.ErrorHandler == nil {
app.Settings.ErrorHandler = func(ctx *Ctx) {
app.Settings.ErrorHandler = func(ctx *Ctx, err error) {
code := StatusInternalServerError
if e, ok := ctx.Error().(*Error); ok {
if e, ok := err.(*Error); ok {
code = e.Code
}
ctx.Status(code).SendString(ctx.Error().Error())
ctx.Status(code).SendString(err.Error())
}
}
}
@ -558,7 +558,7 @@ func (app *App) init() *App {
} else {
ctx.err = ErrBadRequest
}
app.Settings.ErrorHandler(ctx) // ctx.Route() not available
app.Settings.ErrorHandler(ctx, ctx.err) // ctx.Route() not available
app.ReleaseCtx(ctx)
},
}

View File

@ -53,7 +53,7 @@ func Test_App_ErrorHandler(t *testing.T) {
func Test_App_ErrorHandler_Custom(t *testing.T) {
app := New(&Settings{
ErrorHandler: func(ctx *Ctx) {
ErrorHandler: func(ctx *Ctx, err error) {
ctx.Status(200).SendString("Hi, I'm an custom error!")
},
})

4
ctx.go
View File

@ -597,7 +597,7 @@ func (ctx *Ctx) Next(err ...error) {
if len(err) > 0 {
ctx.Fasthttp.Response.Header.Reset()
ctx.err = err[0]
ctx.app.Settings.ErrorHandler(ctx)
ctx.app.Settings.ErrorHandler(ctx, ctx.err)
return
}
@ -838,7 +838,7 @@ func (ctx *Ctx) SendFile(file string, compress ...bool) {
var err error
if file, err = filepath.Abs(file); err != nil {
ctx.err = err
ctx.app.Settings.ErrorHandler(ctx)
ctx.app.Settings.ErrorHandler(ctx, ctx.err)
return
}
if hasTrailingSlash {