• 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
    
  • 相关阅读:
    Selenium Page object models Java
    Windows提权方法论
    Stable DIffusion 炫酷应用 | AI嵌入艺术字+光影光效
    除镍树脂-HP4020
    SpringBoot打包部署最佳实践
    微信支付业务
    原生微信小程序中进行 API 请求
    数据分析实战应用案例精讲-【概念篇】物流行业数据分析(附Python和Java实现代码)
    nodejs如何删除指定文件夹的图片
    鲜花商城|基于Springboot实现鲜花商城系统
  • 原文地址:https://www.cnblogs.com/a-xu/p/18158513