I'm using Go and Gin Gonic to test and exercise some basics in Go. I first did some syntax and basis exercising already.
I've a main.go
(using Gin Gonic) in which I define paths like r.GET(/todo, handler)
. I've a hander.go
in which I describe the handlers like this:
func GetTodoListHandler(c *gin.Context) {
c.JSON(http.StatusOK, todo.Get())
}
At last I have some todo/todo.go
where I define my todo struct and functions.
Now my question, till what stage do I have to return errors?
In my todo/todo.go
I have the Get()
function. It uses another helper function which can have a possible error e.g.
location, err := helper(blabla)
if err != nil {
// for a pointer we can return a nil
return nil, err
}
Now should I return the possible error from the helper function to the Get
function and from the get function back to the handler
function or not? Till what stage do I have to return these errors, is it always till the handler?
I would do this:
func GetTodoListHandler(c *gin.Context) {
list, err := todo.Get()
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
}
c.JSON(http.StatusOK, list)
}
and have todo.Get
return (list, error).
Your http handlers, like GetTodoListHandler
, should never return the errors, but send responses/status codes to the client.