You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/middleware/recovery/recovery.go

63 lines
1.6 KiB

4 years ago
package recovery
import (
"context"
"runtime"
"time"
4 years ago
1 year ago
"gitea.drugeyes.vip/pharnexbase/kratos/v2/errors"
"gitea.drugeyes.vip/pharnexbase/kratos/v2/log"
"gitea.drugeyes.vip/pharnexbase/kratos/v2/middleware"
4 years ago
)
// Latency is recovery latency context key
type Latency struct{}
// ErrUnknownRequest is unknown request error.
var ErrUnknownRequest = errors.InternalServer("UNKNOWN", "unknown request error")
4 years ago
// HandlerFunc is recovery handler func.
type HandlerFunc func(ctx context.Context, req, err interface{}) error
// Option is recovery option.
type Option func(*options)
type options struct {
handler HandlerFunc
}
// WithHandler with recovery handler.
func WithHandler(h HandlerFunc) Option {
return func(o *options) {
o.handler = h
}
}
// Recovery is a server middleware that recovers from any panics.
func Recovery(opts ...Option) middleware.Middleware {
op := options{
4 years ago
handler: func(ctx context.Context, req, err interface{}) error {
return ErrUnknownRequest
4 years ago
},
}
for _, o := range opts {
o(&op)
4 years ago
}
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
startTime := time.Now()
4 years ago
defer func() {
if rerr := recover(); rerr != nil {
buf := make([]byte, 64<<10) //nolint:gomnd
4 years ago
n := runtime.Stack(buf, false)
buf = buf[:n]
log.Context(ctx).Errorf("%v: %+v\n%s\n", rerr, req, buf)
ctx = context.WithValue(ctx, Latency{}, time.Since(startTime).Seconds())
err = op.handler(ctx, req, rerr)
4 years ago
}
}()
return handler(ctx, req)
}
}
}