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. spannerlib优雅go异常处理

    2024-05-01 07:44:02       32 阅读
  2. Go异常处理

    2024-05-01 07:44:02       42 阅读
  3. Go 处理错误&异常

    2024-05-01 07:44:02       38 阅读
  4. 88.Go设计优雅错误处理

    2024-05-01 07:44:02       53 阅读
  5. Go语言异常处理方式

    2024-05-01 07:44:02       42 阅读
  6. 96.Go设计优雅错误处理(带堆栈信息)

    2024-05-01 07:44:02       38 阅读
  7. Go 优雅处理goroutines错误

    2024-05-01 07:44:02       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-01 07:44:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-01 07:44:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-01 07:44:02       82 阅读
  4. Python语言-面向对象

    2024-05-01 07:44:02       91 阅读

热门阅读

  1. k8s 日常维护命令简介

    2024-05-01 07:44:02       39 阅读
  2. k8s中deployment和StatefulSet构建的pod的区别

    2024-05-01 07:44:02       25 阅读
  3. 【C++之多态的知识】

    2024-05-01 07:44:02       30 阅读
  4. 阿里云详细介绍,与AWS和GCP比较

    2024-05-01 07:44:02       33 阅读
  5. 【测试思考】高覆盖的测试用例不只要方法

    2024-05-01 07:44:02       41 阅读
  6. Harbor服务器停电重启后用户不能登陆怎么办?

    2024-05-01 07:44:02       37 阅读
  7. 文件导入导出【开发实践】

    2024-05-01 07:44:02       41 阅读
  8. 算法二分查找(C语言版)

    2024-05-01 07:44:02       33 阅读
  9. http作业

    2024-05-01 07:44:02       37 阅读
  10. Ae 中 Range Selector 和 Expression Selector 有什么区别?

    2024-05-01 07:44:02       32 阅读
  11. 每天学习一个Linux命令之ldconfig

    2024-05-01 07:44:02       33 阅读