Skip to content

Commit

Permalink
middleware: add context arg to the Recover
Browse files Browse the repository at this point in the history
  • Loading branch information
demget committed Apr 6, 2024
1 parent af50a95 commit a26ba9f
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,26 +32,28 @@ func IgnoreVia() tele.MiddlewareFunc {
}
}

type RecoverFunc = func(error, tele.Context)

// Recover returns a middleware that recovers a panic happened in
// the handler.
func Recover(onError ...func(error)) tele.MiddlewareFunc {
func Recover(onError ...RecoverFunc) tele.MiddlewareFunc {
return func(next tele.HandlerFunc) tele.HandlerFunc {
return func(c tele.Context) error {
var f func(error)
var f RecoverFunc
if len(onError) > 0 {
f = onError[0]
} else {
f = func(err error) {
c.Bot().OnError(err, nil)
f = func(err error, c tele.Context) {
c.Bot().OnError(err, c)
}
}

defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
f(err)
f(err, c)
} else if s, ok := r.(string); ok {
f(errors.New(s))
f(errors.New(s), c)
}
}
}()
Expand Down

0 comments on commit a26ba9f

Please sign in to comment.