Table of Contents
go-try
is a package that allows you to use try/catch
block in Go.
This project is still in its early stages, so any thoughts and feedback are very welcome!
Many Go developers get tired of dealing with errors because there are too many errors to handle one by one, which is intuitive and effective, but really annoying.
I've been trying to find out if Go has an error handling method like
try/catch
, I think that would probably be a lot easier, but unfortunately, I
couldn't find any package that's easy to use.
So I tried to make one myself, taking inspiration from the try/catch
syntax,
then go-try
was born!
go get github.com/ez4o/go-try
Try(func () {
...
ThrowOnError(ce)
...
ThrowOnError(err)
...
}).Catch(func (ce CustomError) {
...
}).Catch(func (e error, st *StackTrace) {
...
st.Print()
})
Name | Description |
---|---|
Try() |
Takes func () , wrap your code here! |
Catch() |
Takes func (any) or func (any, *StackTrace) , and it will only accept the error type you have declared. You can accept second parameter, which is the stack trace begin from the last ThrowOnError() . |
ThrowOnError() |
Takes any . Will only throw an error when the parameter is not nil . |
st.Print() |
If you have declared the second parameter st *StackTrace , you can print the stack trace using st.Print() . |
Let's say you want to fetch JSON from a url and unmarshal it, you can simply write it like this:
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
. "github.com/ez4o/go-try"
)
func main() {
Try(func() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
ThrowOnError(err)
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
ThrowOnError(err)
var data []map[string]interface{}
err = json.Unmarshal(b, &data)
ThrowOnError(err)
fmt.Println(data)
}).Catch(func(e error, st *StackTrace) {
fmt.Println(e)
st.Print()
})
}
For more examples, head over to https://github.com/ez4o/go-try/tree/main/.examples!
- Implement catching errors of different types.
- Tests
- CI
See the open issues for a full list of proposed features (and known issues).
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
- Fork the Project
- Create your Feature Branch (
git checkout -b feat/amazing-feature
) - Commit your Changes with Conventional Commits
- Push to the Branch (
git push origin feat/amazing-feature
) - Open a Pull Request
Distributed under the MIT License. See LICENSE for more information.
- HSING-HAN, WU (Xyphuz)
- Mail me: [email protected]
- About me: https://about.xyphuz.com
- GitHub: https://github.com/wst24365888