package main
import (
"fmt"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"net/http"
)
var Db *gorm.DB
type Dade1 struct {
Id int
Dade string
Dada string
}
// 初始化数据库连接
func init() {
dsn := "root:root@tcp(localhost:3306)/dade2?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
// db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("连接失败")
}
// 连接成功后,可以进行数据库操作
fmt.Println("连接成功")
Db = db
}
func main() {
var dade []Dade1
Db.Raw("select * from dade1").Find(&dade)
fmt.Println("大得")
fmt.Println(dade)
//开启事务
tx := Db.Begin()
Try(func() {
if err := tx.Table("dade1").Create(map[string]interface{}{"dade": 6666}).Error; err != nil {
// 发生错误时回滚事务
//tx.Rollback()
fmt.Println("插入失败1")
panic(err)
}
if err := tx.Table("dade1").Create(map[string]interface{}{"dade3": 6666}).Error; err != nil {
// 发生错误时回滚事务
//tx.Rollback()
fmt.Println("插入失败2")
panic(err)
}
//dades()
fmt.Println("这里")
//panic("test panic")
// 提交事务
tx.Commit()
}, func(err interface{}) {
tx.Rollback()
fmt.Println("出错了")
fmt.Println(err)
})
fmt.Println("好好")
router := gin.Default()
router.Use(Recovery())
router.GET("/test", func(c *gin.Context) {
// 模拟触发 panic
panic("This is a panic")
fmt.Println("进不来了")
})
router.GET("/test2", func(c *gin.Context) {
// 模拟触发 panic
fmt.Println("大得")
})
router.Run("0.0.0.0:8000")
}
func Recovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
fmt.Println("出错啦")
// 可以在这里记录错误日志
c.AbortWithStatus(http.StatusInternalServerError)
c.JSON(200, "出错啦")
}
}()
c.Next()
}
}
func dades() {
s := 2
w := 0
dades := s / w
fmt.Println(dades)
}
func Try(fun func(), handler func(interface{})) {
defer func() {
if err := recover(); err != nil {
handler(err)
}
}()
fun()
}
标签:err,fmt,事务处理,func,Println,gin,错误处理,panic
From: https://blog.csdn.net/qq_34631220/article/details/142300800