error4.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // This file contains the code snippets included in "Error Handling and Go."
  5. package main
  6. import (
  7. "net/http"
  8. "text/template"
  9. )
  10. type appError struct {
  11. Error error
  12. Message string
  13. Code int
  14. }
  15. // STOP OMIT
  16. type appHandler func(http.ResponseWriter, *http.Request) *appError
  17. func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  18. if e := fn(w, r); e != nil { // e is *appError, not error.
  19. c := appengine.NewContext(r)
  20. c.Errorf("%v", e.Error)
  21. http.Error(w, e.Message, e.Code)
  22. }
  23. }
  24. // STOP OMIT
  25. func viewRecord(w http.ResponseWriter, r *http.Request) *appError {
  26. c := appengine.NewContext(r)
  27. key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil)
  28. record := new(Record)
  29. if err := datastore.Get(c, key, record); err != nil {
  30. return &appError{err, "Record not found", 404}
  31. }
  32. if err := viewTemplate.Execute(w, record); err != nil {
  33. return &appError{err, "Can't display record", 500}
  34. }
  35. return nil
  36. }
  37. // STOP OMIT
  38. func init() {
  39. http.Handle("/view", appHandler(viewRecord))
  40. }
  41. type ap struct{}
  42. func (ap) NewContext(*http.Request) *ctx { return nil }
  43. type ctx struct{}
  44. func (*ctx) Errorf(string, ...interface{}) {}
  45. var appengine ap
  46. type ds struct{}
  47. func (ds) NewKey(*ctx, string, string, int, *int) string { return "" }
  48. func (ds) Get(*ctx, string, *Record) error { return nil }
  49. var datastore ds
  50. type Record struct{}
  51. var viewTemplate *template.Template
  52. func main() {}