You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package builtin
import (
"fmt"
"runtime/debug"
ctxpkg "github.com/noahlann/nnet/pkg/context"
routerpkg "github.com/noahlann/nnet/pkg/router"
)
// RecoveryMiddleware 恢复中间件( 捕获panic)
func RecoveryMiddleware ( ) routerpkg . Handler {
return func ( ctx ctxpkg . Context ) error {
defer func ( ) {
if r := recover ( ) ; r != nil {
fmt . Printf ( "Panic recovered: %v\n%s\n" , r , debug . Stack ( ) )
// 可以在这里记录错误或发送错误响应
ctx . Response ( ) . WriteString ( fmt . Sprintf ( "Internal Server Error: %v\n" , r ) )
}
} ( )
// 中间件本身不执行任何操作, panic恢复会在defer中处理
return nil
}
}
// RecoveryMiddlewareWithHandler 带错误处理器的恢复中间件
func RecoveryMiddlewareWithHandler ( handler func ( ctx ctxpkg . Context , panic interface { } ) ) routerpkg . Handler {
return func ( ctx ctxpkg . Context ) error {
defer func ( ) {
if r := recover ( ) ; r != nil {
if handler != nil {
handler ( ctx , r )
} else {
fmt . Printf ( "Panic recovered: %v\n%s\n" , r , debug . Stack ( ) )
ctx . Response ( ) . WriteString ( fmt . Sprintf ( "Internal Server Error: %v\n" , r ) )
}
}
} ( )
return nil
}
}