From 5b1d414ba23937e7fe1eba74547a7acf33e9c5a6 Mon Sep 17 00:00:00 2001 From: Joe Robinson Date: Mon, 21 Jul 2014 11:51:34 +0100 Subject: Added some error checking --- poll.go | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) (limited to 'poll.go') diff --git a/poll.go b/poll.go index 803cf6c..275aa21 100644 --- a/poll.go +++ b/poll.go @@ -1,7 +1,8 @@ package main import "github.com/mxk/go-sqlite/sqlite3" -import "fmt" +import "errors" +import "strconv" type Poll struct { id int64 @@ -14,10 +15,15 @@ func addPoll(db *sqlite3.Conn, title string, options []string, nick string) (int user := getUserForName(db, nick) if (user.id == 0) { - createUser(db, nick, false) - user = getUserForName(db, nick) + var err error + user, err = createUser(db, nick, false) + + if (err != nil) { + return 0, err + } } + args := sqlite3.NamedArgs{"$a": title, "$b": user.id} sql := "INSERT INTO polls (title, user_id) VALUES ($a, $b)" @@ -53,7 +59,7 @@ func addOption(db *sqlite3.Conn, text string, pollId int64) error { return nil } -func getPollFromTitle(db *sqlite3.Conn, title string) Poll { +func getPollFromTitle(db *sqlite3.Conn, title string) (Poll, error) { args := sqlite3.NamedArgs{"$a": title} sql := "SELECT * FROM polls WHERE title = $a" @@ -65,15 +71,15 @@ func getPollFromTitle(db *sqlite3.Conn, title string) Poll { s.Scan(&rowid, row) // Assigns 1st column to rowid, the rest to row poll := Poll{id:rowid, title:row["title"].(string), userId:row["user_id"].(int64)} - return poll + return poll, nil } - //If we get here there are no matching users - return Poll{id:0, title:"", userId:0} + //If we get here there are no matching polls, return an error + return Poll{id:0, title:"", userId:0}, errors.New("No poll found with title '" + title +"'") } -func getPollFromId(db *sqlite3.Conn, id int) Poll { +func getPollFromId(db *sqlite3.Conn, id int) (Poll, error) { args := sqlite3.NamedArgs{"$a": id} sql := "SELECT * FROM polls WHERE id = $a" @@ -85,18 +91,23 @@ func getPollFromId(db *sqlite3.Conn, id int) Poll { s.Scan(&rowid, row) // Assigns 1st column to rowid, the rest to row poll := Poll{id:rowid, title:row["title"].(string), userId:row["user_id"].(int64)} - return poll + return poll, nil } - //If we get here there are no matching users - return Poll{id:0, title:"", userId:0} + //If we get here there are no matching polls, return an error + return Poll{id:0, title:"", userId:0}, errors.New("No poll found with ID " + strconv.Itoa(id)) } func deletePoll(db *sqlite3.Conn, id int, nick string) error { user := getUserForName(db, nick) - poll := getPollFromId(db, id) + + poll, err := getPollFromId(db, id) + + if (err != nil) { + return err + } if (user.isAdmin || poll.userId == user.id) { @@ -109,8 +120,7 @@ func deletePoll(db *sqlite3.Conn, id int, nick string) error { return nil } } else { - fmt.Println("denied") - return nil + return errors.New("You do not have permission to delete this poll") } -- cgit v1.2.3