0 Star 0 Fork 41

景德真人/lessgo

forked from andeyalee/lessgo 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
recover.go 1.81 KB
一键复制 编辑 原始数据 按行查看 历史
henrylee2cn 提交于 2016-04-08 13:58 . API changes from to with
package lessgo
import (
"fmt"
"runtime"
"github.com/lessgo/lessgo/logs/color"
)
type (
// RecoverConfig defines the config for recover middleware.
RecoverConfig struct {
// StackSize is the stack size to be printed.
// Optional with default value as 4k.
StackSize int
// DisableStackAll disables formatting stack traces of all other goroutines
// into buffer after the trace for the current goroutine.
// Optional with default value as false.
DisableStackAll bool
// DisablePrintStack disables printing stack trace.
// Optional with default value as false.
DisablePrintStack bool
}
)
var (
// DefaultRecoverConfig is the default recover middleware config.
DefaultRecoverConfig = RecoverConfig{
StackSize: 4 << 10, // 4 KB
DisableStackAll: false,
DisablePrintStack: false,
}
)
// Recover returns a middleware which recovers from panics anywhere in the chain
// and handles the control to the centralized HTTPErrorHandler.
func Recover() MiddlewareFunc {
return RecoverWithConfig(DefaultRecoverConfig)
}
// RecoverWithConfig returns a recover middleware from config.
// See `Recover()`.
func RecoverWithConfig(config RecoverConfig) MiddlewareFunc {
// Defaults
if config.StackSize == 0 {
config.StackSize = DefaultRecoverConfig.StackSize
}
return func(next HandlerFunc) HandlerFunc {
return func(c Context) error {
defer func() {
if r := recover(); r != nil {
var err error
switch r := r.(type) {
case error:
err = r
default:
err = fmt.Errorf("%v", r)
}
stack := make([]byte, config.StackSize)
length := runtime.Stack(stack, !config.DisableStackAll)
if !config.DisablePrintStack {
c.Logger().Error("[%s] %s %s", color.Red("PANIC RECOVER"), err, stack[:length])
}
c.Error(err)
}
}()
return next(c)
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/szpzs/lessgo.git
git@gitee.com:szpzs/lessgo.git
szpzs
lessgo
lessgo
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385