当前位置:网站首页>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")
}边栏推荐
- FPGA - 7系列 FPGA内部结构之Clocking -01- 时钟架构概述
- Seven major technical updates that developers should pay most attention to on build 2022
- 穿越派与贸大合作,为大学生增添效率
- C language beginner level - realize the minesweeping game
- OpenGL es: (2) relationship between OpenGL es, EGL and glsl
- 69 cesium code datasource loading geojson
- 让田头村变甜头村的特色农产品是仙景芋还是白菜
- 4GB大文件,如何实时远程传输和共享?
- Leetcode Max rectangle, Max square series 84 85. 221. 1277. 1725. (monotonic stack, dynamic programming)
- 论文学习记录随笔 多标签之LSML
猜你喜欢

jdbc 数据库操作

让厦门灌口镇田头村变甜头村的特色农产品之一是蚂蚁新村

2022 年面向初学者的 10 大免费 3D 建模软件

【笔记】电商订单数据分析实战

扩展点系列之SmartInstantiationAwareBeanPostProcessor确定执行哪一个构造方法 - 第432篇

Crossing pie · pie pan + Mountain duck = local data management
![Pit of kotlin bit operation (bytes[i] and 0xff error)](/img/2c/de0608c29d8af558f6f8dab4eb7fd8.png)
Pit of kotlin bit operation (bytes[i] and 0xff error)

Ucosiii --- engineering transplantation

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

从诺奖知“边缘计算”的未来!
随机推荐
OpenGL es: (3) EGL, basic steps of EGL drawing, eglsurface, anativewindow
DEV XPO对比之UOW
Infinite horizontal marble game
TIDB数据库特性总结
win10、win11中Elan触摸板滚动方向反转、启动“双指点击打开右键菜单“、“双指滚动“
c# Xml帮助类
C XML help class
π盘,让您电脑变成个人的私有云
Code shoe set - mt3114 · interesting balance - explain it with examples
栈题目:解析布尔表达式
4GB大文件,如何实时远程传输和共享?
Excel dynamic chart
MySQL怎么存储emoji?
Preliminary level of C language -- selected good questions on niuke.com
Call us special providers of personal cloud services for College Students
蚂蚁新村田头村变甜头村 让厦门灌口镇田头村变甜头村的特色农产品之一是
Continue to learn MySQL
What if the data in the cloud disk is harmonious?
excel動態圖錶
扩展点系列之SmartInstantiationAwareBeanPostProcessor确定执行哪一个构造方法 - 第432篇