spannerlib优雅的go异常处理

蹩脚的go 异常处理

一般写go的人,如果他不是写算法,正常写业务代码的话,可能都会为优雅的异常处理而烦恼,因为脑子抽筋的go设计者们,总是感觉语法糖是一种很低级的东西。但是在我们大多数公司的业务逻辑中,没有语法糖让代码非常丑陋,不易于维护。
如何让go 代码更具有可读性,哪么就要给go加糖!

引入spannerlib

go get github.com/lingdor/spannerlib

异常处理

通常我们需要这么写代码

num,numErr:=strconv.Itoa("123")
if numErr!=nil {
    panic(numErr)
}
age,ageErr:=strconv.Itoa("18")
if ageErr!=nil {
    panic(ageErr)
}

优雅起来

ginRoute.use(func ContextInit() gin.HandlerFunc {
	return func(c *gin.Context) {
		if err := recover(); err != nil {
		log.Error(fmt.Sprintf("%v", err))
		if msg, ok := E.GetErrorData[string](err); ok {
			c.JSON(http.StatusOK, gin.H{
				"code":    1,
				"message": msg,
			})
			return
		}
	}
})


ginRoute.Get("/hello",func(c *gin.Context){
	
	year := E.Must1(strconv.Atoi(c.Query("year")))
	month := E.Must1(strconv.Atoi(c.Query("month))
 //others
})

//or
ginRoute.Get("/hello2",func(c *gin.Context){
 
 year := E.Catch1(strconv.Atoi(c.Query("year"))).IfErrorData("year格式不正确").Must()
 month := E.Catch1(strconv.Atoi(c.Query("month"))).IfErrorData("month格式不正确").Must()
 // others
})


增加堆栈打印

err:=fmt.Errorf("123")
err:=errors.Wrap(err,0,"msg")

fmt.printf("%v",err)

output

Exception MSG
testing.tRunner(/usr/local/go/src/testing/testing.go:1689)

字符处理

判断字符是否开始于

if str.StartWith("hello world","hello") {
//true
}

2.2. 通过字符实现字符截取

fmt.Println(E.Must1(StringPick("123", "", "")))

output:


123

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值