Skip to content

Commit ad66ed8

Browse files
committed
better error handling
1 parent 82da188 commit ad66ed8

File tree

3 files changed

+53
-29
lines changed

3 files changed

+53
-29
lines changed

db.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@ package main
22

33
import (
44
"database/sql"
5-
"log"
5+
6+
"github.com/rs/zerolog/log"
67
)
78

89
// InitDB create the database table and indexes
910
func InitDB(dsn string) *sql.DB {
1011
db, err := sql.Open("sqlite3", dsn)
1112
if err != nil {
12-
log.Fatal("error db")
13+
log.Fatal().Msg("database init error")
1314
}
1415
statement, _ := db.Prepare(`CREATE TABLE IF NOT EXISTS annotations (
1516
id INTEGER PRIMARY KEY,

handlers.go

Lines changed: 45 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,19 @@ func List(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
3838

3939
rows, err := db.Query("SELECT body FROM annotations where target=?", canvas[0])
4040
if err != nil {
41-
log.Fatal().Err(err)
41+
log.Error().Err(err).Str("action", "list").Msg("db error")
42+
w.WriteHeader(http.StatusInternalServerError)
43+
w.Write([]byte("500"))
44+
return
4245
}
4346
defer rows.Close()
4447
for rows.Next() {
4548
err := rows.Scan(&body)
4649
if err != nil {
47-
log.Fatal().Err(err)
50+
log.Error().Err(err).Str("action", "list").Msg("db error")
51+
w.WriteHeader(http.StatusInternalServerError)
52+
w.Write([]byte("500"))
53+
return
4854
}
4955
list.Resources = append(list.Resources, body)
5056
}
@@ -56,30 +62,31 @@ func List(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
5662
w.Header().Set("Content-Type", "application/json")
5763
enc := json.NewEncoder(w)
5864
if err := enc.Encode(list); err != nil {
59-
fmt.Println(err)
65+
log.Error().Err(err).Str("action", "list").Str("canvas", canvas[0]).Msg("annotation list error")
66+
w.WriteHeader(http.StatusInternalServerError)
67+
w.Write([]byte("500"))
68+
return
6069
}
6170

6271
}
6372

6473
// Get retrieve a single annotation with database id
65-
// TODO: retrieve with annotation id
74+
// NOTE: just for test, not used by mirador
6675
func Get(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
6776
w.Header().Set("Content-Type", "application/json")
6877

6978
var body string
70-
rows, err := db.Query("SELECT body FROM annotations where id=?", ps.ByName("id"))
79+
err := db.QueryRow("SELECT body FROM annotations where id=?", ps.ByName("id")).Scan(&body)
80+
7181
if err != nil {
72-
log.Fatal().Err(err)
73-
}
74-
defer rows.Close()
75-
for rows.Next() {
76-
err := rows.Scan(&body)
77-
if err != nil {
78-
log.Fatal().Err(err)
79-
}
80-
fmt.Fprintf(w, body)
82+
log.Error().Err(err).Str("action", "get").Msg("db error")
83+
w.WriteHeader(http.StatusInternalServerError)
84+
w.Write([]byte("500"))
85+
return
8186
}
8287

88+
w.Header().Set("Content-Type", "application/json")
89+
fmt.Fprintf(w, body)
8390
}
8491

8592
// Delete an annotation
@@ -89,14 +96,20 @@ func Delete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
8996
var anno string
9097
err := db.QueryRow("SELECT body FROM annotations where annoid = ?", ps.ByName("id")).Scan(&anno)
9198
if err != nil {
92-
log.Fatal().Err(err)
99+
log.Error().Err(err).Str("action", "delete").Msg("db error")
100+
w.WriteHeader(http.StatusInternalServerError)
101+
w.Write([]byte("500"))
102+
return
93103
}
94104

95105
_, err = db.Exec("DELETE FROM annotations where annoid=?", ps.ByName("id"))
96106
if err != nil {
97-
log.Fatal().Err(err)
107+
log.Error().Err(err).Str("action", "delete").Msg("db error")
108+
w.WriteHeader(http.StatusInternalServerError)
109+
w.Write([]byte("500"))
110+
return
98111
}
99-
log.Info().Str("annotation-id", ps.ByName("id")).Msg("deleted")
112+
log.Info().Str("annotation_id", ps.ByName("id")).Str("action", "delete").Msg("")
100113
w.Header().Set("Content-Type", "application/json")
101114
fmt.Fprintf(w, anno)
102115
}
@@ -106,14 +119,18 @@ func Create(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
106119
body, err := ioutil.ReadAll(r.Body)
107120
defer r.Body.Close()
108121
if err != nil {
109-
http.Error(w, err.Error(), 500)
122+
log.Error().Err(err).Str("action", "create").Msg("")
123+
w.WriteHeader(http.StatusInternalServerError)
124+
w.Write([]byte("500"))
110125
return
111126
}
112127

113128
var annotation Annotation
114129
err = json.Unmarshal(body, &annotation)
115130
if err != nil {
116-
http.Error(w, err.Error(), 500)
131+
log.Error().Err(err).Str("action", "create").Msg("")
132+
w.WriteHeader(http.StatusInternalServerError)
133+
w.Write([]byte("500"))
117134
return
118135
}
119136

@@ -122,7 +139,7 @@ func Create(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
122139
AnnotationWithID, _ := json.Marshal(annotation)
123140
statement, _ := db.Prepare("INSERT INTO annotations (annoid, created_at, target, manifest, body) VALUES (?, ?, ?, ?, ?)")
124141
statement.Exec(annoid, time.Now(), annotation.Canvas(), annotation.Manifest(), AnnotationWithID)
125-
log.Info().Str("annotation-id", annoid).Msg("create")
142+
log.Info().Str("annotation_id", annoid).Str("action", "create").Msg("")
126143

127144
fmt.Fprintf(w, string(AnnotationWithID))
128145
}
@@ -135,16 +152,21 @@ func Update(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
135152
body, err := ioutil.ReadAll(r.Body)
136153
defer r.Body.Close()
137154
if err != nil {
138-
http.Error(w, err.Error(), 500)
155+
log.Error().Err(err).Str("action", "update").Msg("db error")
156+
w.WriteHeader(http.StatusInternalServerError)
157+
w.Write([]byte("500"))
139158
return
140159
}
141160

142161
_, err = db.Exec("UPDATE annotations SET body=? WHERE annoid=?", body, annoid)
143162
if err != nil {
144-
log.Fatal().Err(err)
163+
log.Error().Err(err).Str("action", "update").Msg("db error")
164+
w.WriteHeader(http.StatusInternalServerError)
165+
w.Write([]byte("500"))
166+
return
145167
}
146168

147-
log.Info().Str("annotation-id", annoid).Msg("update")
169+
log.Info().Str("annotation_id", annoid).Str("action", "update").Msg("")
148170

149171
fmt.Fprintf(w, string(body))
150172
}

main.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"github.com/julienschmidt/httprouter"
1111
_ "github.com/mattn/go-sqlite3"
1212
"github.com/mitchellh/go-homedir"
13+
"github.com/rs/zerolog"
1314
"github.com/rs/zerolog/log"
1415
"github.com/zserge/webview"
1516
)
@@ -26,13 +27,13 @@ func init() {
2627
}
2728

2829
func main() {
29-
log.Logger = log.Output(os.Stdout)
30+
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
3031
db = InitDB(annotationsDB)
3132
router := httprouter.New()
3233

3334
ln, err := net.Listen("tcp", "127.0.0.1:0")
3435
if err != nil {
35-
log.Error().Msg("server err")
36+
log.Fatal().Err(err).Msg("server failed to start")
3637
}
3738
defer ln.Close()
3839
go func() {
@@ -49,9 +50,9 @@ func main() {
4950
fileServer.ServeHTTP(w, r)
5051
})
5152

52-
log.Info().Msg("# listening on " + ln.Addr().String())
53+
log.Info().Str("address", "http://"+ln.Addr().String()).Msg("server started")
5354
if err := http.Serve(ln, router); err != nil {
54-
log.Fatal().Err(err).Msg("Startup failed")
55+
log.Fatal().Err(err).Msg("server failed to start")
5556
}
5657

5758
}()

0 commit comments

Comments
 (0)