Created
April 23, 2015 09:26
-
-
Save karlseguin/3fbe1aa749b1e58c485e to your computer and use it in GitHub Desktop.
Find aritcle example for http://openmymind.net/Golangs-Error-Handling-Good-And-Bad/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func LoadArticle(res http.ResponseWriter, req *http.Request) { | |
if article, err := FindArticleById(...) | |
if err != nil { | |
handleError(res, err) | |
return | |
} | |
if article == nil { | |
handleNotFound(res, err) | |
} | |
} | |
func FindArticleById(id string) (*Article, error) { | |
conn, err := db.Open() | |
if err != nil { | |
return nil, err | |
} | |
var ... | |
err := conn.QueryRow("find_article_by_id", id).Scan(.....) | |
if err != nil { | |
return nil, err | |
} | |
return &Article{....}, nil | |
} |
egonelbre
commented
Apr 23, 2015
With GeneralErrorHandling:
package article
var NotFound = errors.New("Not found.")
func ShowArticle(w http.ResponseWriter, r *http.Request) {
if article, err := FindByID(r.FormValue("id")); err == nil {
GeneralErrorHandler(w, err)
return
}
fmt.Fprintf(w, "%s", article)
}
func LoadByID(id string) (*Article, error) {
conn, err := db.Open()
if err != nil {
return nil, err
}
var article Article
err = conn.QueryRow("find_article_by_id", id).Scan(&article)
if err != nil {
// check here whether it actually is a not found error...
return nil, NotFound
}
return &article, nil
}
With panicking, there should be some sort of recovery happening at the upper level...
package article
var NotFound = errors.New("Not found.")
func ShowArticle(w http.ResponseWriter, r *http.Request) {
article := FindByID(r.FormValue("id"))
fmt.Fprintf(w, "%s", article)
}
func LoadByID(id string) *Article {
conn, err := db.Open()
if err != nil {
panic(err)
}
var article Article
err = conn.QueryRow("find_article_by_id", id).Scan(&article)
if err != nil {
// check here whether it actually is a not found error...
panic(NotFound)
}
return &article
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment