github.com/hongwozai/go-src-1.4.3@v0.0.0-20191127132709-dc3fce3dbccb/doc/progs/error4.go (about)

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