当前位置:网站首页>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")
}边栏推荐
- MinIO纠错码、分布式MinIO集群搭建及启动
- 69 Cesium代码datasource加载geojson
- PLA not pasted on the bed: 6 simple solutions
- Thesis learning record essay multi label lift
- three. JS summary
- C language beginner level - realize the minesweeping game
- 指数法和Random Forest实现山东省丰水期地表水体信息
- 数据库er图组成要素
- 数据库问题,如何优化Oracle SQL查询语句更快,效率更高
- Smartinstantiationawarebeanpostprocessor of the extension point series determines which construction method to execute - Chapter 432
猜你喜欢

68 Cesium代码datasource加载czml

linux 关闭redis 进程 systemd+

从诺奖知“边缘计算”的未来!

TIDB数据库特性总结

Infinite horizontal marble game

Cjc8988 Low Power Stereo codec with 2 stereo headphone drivers

Through cooperation with the University of international trade, we can increase efficiency for college students

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

LeetCode 最大矩形,最大正方形系列 84. 85. 221. 1277. 1725. (单调栈,动态规划)

芯片,建立在沙粒上的帝国!
随机推荐
Linux closes the redis process SYSTEMd+
Excel dynamic chart
FPGA - 7系列 FPGA内部结构之Clocking -02- 时钟布线资源
Code shoe set - mt3149 · and - the data is not very strong. Violent pruning can deceive AC
TiDB单机模拟部署生产环境集群(闭坑实践,亲测有效)
健康照明中应用的LED照明灯
DEV XPO对比之XAF BO
表格中el-tooltip 实现换行展示
利用百度地图查询全国地铁线路
从诺奖知“边缘计算”的未来!
C language beginner level - realize the minesweeping game
excel動態圖錶
Beauty of Mathematics - Application of Mathematics
CJC8988带2个立体声耳机驱动器的低功率立体声编解码器
让田头村变甜头村的特色农产品是仙景芋还是白菜
穿越派 你的数据云行
ArcServer密码重置(账号不可以重置)
Database problems, how to optimize Oracle SQL query statements faster and more efficient
芯片,建立在沙粒上的帝国!
指数法和Random Forest实现山东省丰水期地表水体信息