当前位置:网站首页>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")
}边栏推荐
猜你喜欢

TiDB单机模拟部署生产环境集群(闭坑实践,亲测有效)

喊我们大学生个人云服务特供商
![kotlin位运算的坑(bytes[i] and 0xff 报错)](/img/2c/de0608c29d8af558f6f8dab4eb7fd8.png)
kotlin位运算的坑(bytes[i] and 0xff 报错)

Know the future of "edge computing" from the Nobel prize!

穿越派·派盘 + 思源笔记 = 私人笔记本

Small guide for rapid completion of mechanical arm (VI): stepping motor driver

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

表格中el-tooltip 实现换行展示

PLA不粘贴在床上:6个简单的解决方案

基于LabVIEW的计时器
随机推荐
表格中el-tooltip 实现换行展示
Oracle sequence + trigger
Pla ne colle pas sur le lit: 6 solutions simples
MySQL中 in 和 exists 的区别
68 Cesium代码datasource加载czml
Infinite horizontal marble game
Advanced drawing skills of Excel lecture 100 (1) - use Gantt chart to show the progress of the project
Know the future of "edge computing" from the Nobel prize!
利用百度地图查询全国地铁线路
Geoffrey Hinton: my 50 years of in-depth study and Research on mental skills
浏览器端保存数据到本地文件
SOE spatial analysis server MySQL and PostGIS geospatial database of Postgres anti injection attack
千万不要把笔记视频乱放!
freeswitch拨打分机号
El tooltip in the table realizes line breaking display
4GB大文件,如何实时远程传输和共享?
Servlet
ONEFLOW source code parsing: automatic inference of operator signature
el-table 动态表头渲染 固定第一列 高度问题
Linux closes the redis process SYSTEMd+