当前位置:网站首页>golang panic recover自定义异常处理
golang panic recover自定义异常处理
2022-07-01 06:05:00 【风一样的男子&】
- panic
panic 这个词,在英语中具有恐慌、恐慌的等意思;panic 关键字主要用于主动抛出异常,类似 Python中的raise关键字
- recover
recover 这个词,在英语中具有恢复、复原等意思;从字面意思理解的话,在 Go 语言中,代表将程序状态从严重的错误中恢复到正常状态。Go语言中 recover 关键字主要用于捕获异常,让程序回到正常状态,类似Python中的except,用来捕获异常,可以在具体异常处理中做特殊操作。
- Custom Recovery behavior 自定义异常捕获行为
func main() {
// Creates a router without any middleware by default
r := gin.New()
// Global middleware
// Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.
// By default gin.DefaultWriter = os.Stdout
r.Use(gin.Logger())
// Recovery middleware recovers from any panics and writes a 500 if there was one.
r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
if err, ok := recovered.(string); ok {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.AbortWithStatus(http.StatusInternalServerError)
}))
r.GET("/panic", func(c *gin.Context) {
// panic with a string -- the custom middleware could save this to a database or report it to the user
panic("foo")
})
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "ohai")
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}边栏推荐
- Enter an expression (expressed as a string) and find the value of this expression.
- OpenGL es: (4) detailed explanation of EGL API (Continued)
- Multi label lsml for essay learning records
- MySQL中 in 和 exists 的区别
- In win10 and win11, the scroll direction of Elan touch panel is reversed, and "double finger click to open the right-click menu" and "double finger scroll" are started“
- kotlin位运算的坑(bytes[i] and 0xff 报错)
- 穿越派·派盘 + Mountain Duck = 数据本地管理
- Thesis learning record essay multi label lift
- excel可视化
- SystemVerilog学习-09-进程间同步、通信和虚方法
猜你喜欢

FPGA - 7系列 FPGA内部结构之Clocking -02- 时钟布线资源

【文件系统】如何在ubi之上运行squashfs

Some errors encountered in MySQL data migration

On the first day of the new year, 3000 Apache servers went down

three.js小结

69 cesium code datasource loading geojson

ONEFLOW source code parsing: automatic inference of operator signature

Seven major technical updates that developers should pay most attention to on build 2022

3D printer threading: five simple solutions

Scope data export mat
随机推荐
MySQL怎么存储emoji?
解决麒麟V10上传文件乱码问题
srpingboot security demo
SystemVerilog学习-09-进程间同步、通信和虚方法
2022 年面向初学者的 10 大免费 3D 建模软件
机械臂速成小指南(六):步进电机驱动器
Continue to learn MySQL
PLA not pasted on the bed: 6 simple solutions
喊我们大学生个人云服务特供商
蚂蚁新村田头村变甜头村 让厦门灌口镇田头村变甜头村的特色农产品之一是
3D打印机穿线:5种简单的解决方案
CJC8988带2个立体声耳机驱动器的低功率立体声编解码器
云盘里资料被和谐了,怎么办?
DEV XPO对比之XAF BO
Thoughts on a "01 knapsack problem" expansion problem
What if the data in the cloud disk is harmonious?
无限水平大理石游戏
论文学习记录随笔 多标签之GLOCAL
DHT11 温湿度传感器
Database problems, how to optimize Oracle SQL query statements faster and more efficient