1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-17 09:57:01 +00:00

add x/errors.RecoveryHandler

This commit is contained in:
Gerasimos (Makis) Maropoulos
2024-01-10 22:17:58 +02:00
parent 06a6e63dd9
commit b2c37e17b4
7 changed files with 55 additions and 41 deletions

View File

@@ -3,7 +3,7 @@ package errors
import "github.com/kataras/iris/v12/context"
// DefaultContextErrorHandler returns a context error handler
// which fires a JSON bad request (400) error message when
// which calls the HandleError on any incoming error when
// a rich rest response failed to be written to the client.
// Register it on Application.SetContextErrorHandler method.
var DefaultContextErrorHandler context.ErrorHandler = new(jsonErrorHandler)
@@ -13,5 +13,5 @@ type jsonErrorHandler struct{}
// HandleContextError completes the context.ErrorHandler interface. It's fired on
// rich rest response failures.
func (e *jsonErrorHandler) HandleContextError(ctx *context.Context, err error) {
InvalidArgument.Err(ctx, err)
HandleError(ctx, err)
}

View File

@@ -3,6 +3,7 @@ package errors
import (
stdContext "context"
"errors"
"fmt"
"io"
"net/http"
@@ -12,6 +13,29 @@ import (
"golang.org/x/exp/constraints"
)
// RecoveryHandler is a middleware which recovers from panics and sends an appropriate error response
// to the logger and the client.
func RecoveryHandler(ctx *context.Context) {
defer func() {
if rec := recover(); rec != nil {
var err error
switch v := rec.(type) {
case error:
err = v
case string:
err = New(v)
default:
err = fmt.Errorf("%v", v)
}
Internal.LogErr(ctx, err)
ctx.StopExecution()
}
}()
ctx.Next()
}
// Handle handles a generic response and error from a service call and sends a JSON response to the client.
// It returns a boolean value indicating whether the handle was successful or not.
// If the error is not nil, it calls HandleError to send an appropriate error response to the client.