当前位置:网站首页>Golang panic recover custom exception handling
Golang panic recover custom exception handling
2022-07-01 06:08:00 【A man like the wind &】
- panic
panic The word , There is panic in English 、 Panic, etc ;panic Keyword is mainly used to actively throw exceptions , similar Python Medium raise keyword
- recover
recover The word , In English, it has the function of restoring 、 Recovery, etc ; Literally , stay Go In language , Represents the restoration of the program state from a serious error to a normal state .Go In language recover The keyword is mainly used to catch exceptions , Return the program to normal , similar Python Medium except, Used to catch exceptions , You can do special operations in specific exception handling .
- Custom Recovery behavior Custom exception capture 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")
}边栏推荐
猜你喜欢

Index method and random forest to realize the information of surface water body in wet season in Shandong Province

Call us special providers of personal cloud services for College Students

Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills

uniapp树形层级选择器

DHT11 温湿度传感器

3D打印机穿线:5种简单的解决方案

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

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

可动的机械挂钟

【文件系统】如何在ubi之上运行squashfs
随机推荐
健康照明中应用的LED照明灯
srpingboot security demo
利用百度地图查询全国地铁线路
FPGA - 7系列 FPGA内部结构之Clocking -01- 时钟架构概述
3D打印机穿线:5种简单的解决方案
ABP 学习解决方案中的项目以及依赖关系
浏览器端保存数据到本地文件
Bat operation FTP upload and download command
论文学习记录随笔 多标签之LIFT
Arcserver password reset (account cannot be reset)
Multi label lsml for essay learning records
Codeforces Round #803 (Div. 2)vp
QT write custom control - self drawn battery
Primary application case of Excel DuPont analyzer
Chip, an empire built on sand!
让厦门灌口镇田头村变“甜头”村的特色农产品之一是
SystemVerilog学习-06-类的封装
Fixed height of the first column in El table dynamic header rendering
DHT11 temperature and humidity sensor
2022 the 8th China International "Internet +" college student innovation and entrepreneurship competition industry proposition track is open for registration!