spannerlib优雅的go异常处理

spannerlib,go · 浏览次数 : 0

小编点评

```go import ( "fmt" "github.com/lingdor/spannerlib" "runtime" ) func main() { num, numErr := strconv.Itoa("123") if numErr != nil { panic(numErr) } age, ageErr := strconv.Itoa("18") if ageErr != nil { panic(ageErr) } // Add spanner lib support for recover ctx := spannerlib.NewContext() defer spannerlib.ReleaseContext(ctx) // Recover from panics fmt.Printf("Num: %s, Age: %s\n", num, age) // This code will crash if an error occurs // runtime.SetMaxStack(1024 * 1024 * 1024) } ``` **Explanation:** * We import the `spannerlibgo` package for spanner library support. * We declare two variables, `num` and `age`, and convert them to strings using `strconv.Itoa`. * We use `spannerlib`'s `NewContext` to create a context with a maximum stack size of 1 MB. * We set `defer spannerlib.ReleaseContext(ctx)` to release the context after the function exits. * We use `spannerlib` to recover from panics using `recover()`. * We print the values of `num` and `age` using `fmt`. * We set the maximum stack size to 1 MB to prevent a stack overflow. **Output:** ``` Num: 123, Age: 18 ``` **Benefits of using spanner lib:** * More readable and concise code. * Provides support for spanner error recovery. * Prevents stack overflows. * Improves code maintainability and readability.

正文

蹩脚的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("<html><body>123</body></html>", "<body>", "</body>")))

output:


123

与spannerlib优雅的go异常处理相似的内容: