1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-22 11:25:59 +00:00

implement mvc HandleError as requested at #1244

Former-commit-id: 58a69f9cffe67c3aa1bab5d9425c5df65e2367ed
This commit is contained in:
Gerasimos (Makis) Maropoulos
2019-04-16 18:01:48 +03:00
parent df3a68255c
commit 0d4d2bd3fa
13 changed files with 145 additions and 363 deletions

View File

@@ -20,6 +20,23 @@ type Result interface {
Dispatch(ctx context.Context)
}
type (
// ErrorHandler is the optional interface to handle errors per hero func,
// see `mvc/Application#HandleError` for MVC application-level error handler registration too.
ErrorHandler interface {
HandleError(ctx context.Context, err error)
}
// ErrorHandlerFunc implements the `ErrorHandler`.
// It describes the type defnition for an error handler.
ErrorHandlerFunc func(ctx context.Context, err error)
)
// HandleError fires when the `DispatchFuncResult` returns a non-nil error.
func (fn ErrorHandlerFunc) HandleError(ctx context.Context, err error) {
fn(ctx, err)
}
var defaultFailureResponse = Response{Code: DefaultErrStatusCode}
// Try will check if "fn" ran without any panics,
@@ -164,7 +181,7 @@ func DispatchCommon(ctx context.Context,
// Result or (Result, error) and so on...
//
// where Get is an HTTP METHOD.
func DispatchFuncResult(ctx context.Context, values []reflect.Value) {
func DispatchFuncResult(ctx context.Context, errorHandler ErrorHandler, values []reflect.Value) {
if len(values) == 0 {
return
}
@@ -294,6 +311,11 @@ func DispatchFuncResult(ctx context.Context, values []reflect.Value) {
content = value
case compatibleErr:
if value != nil { // it's always not nil but keep it here.
if errorHandler != nil {
errorHandler.HandleError(ctx, value)
break
}
err = value
if statusCode < 400 {
statusCode = DefaultErrStatusCode