github.com/razvanm/vanadium-go-1.3@v0.0.0-20160721203343-4a65068e5915/doc/progs/error.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 "encoding/json" 13 "errors" 14 "fmt" 15 "log" 16 "net" 17 "os" 18 "time" 19 ) 20 21 type File struct{} 22 23 func Open(name string) (file *File, err error) { 24 // OMIT 25 panic(1) 26 // STOP OMIT 27 } 28 29 func openFile() { // OMIT 30 f, err := os.Open("filename.ext") 31 if err != nil { 32 log.Fatal(err) 33 } 34 // do something with the open *File f 35 // STOP OMIT 36 _ = f 37 } 38 39 // errorString is a trivial implementation of error. 40 type errorString struct { 41 s string 42 } 43 44 func (e *errorString) Error() string { 45 return e.s 46 } 47 48 // STOP OMIT 49 50 // New returns an error that formats as the given text. 51 func New(text string) error { 52 return &errorString{text} 53 } 54 55 // STOP OMIT 56 57 func Sqrt(f float64) (float64, error) { 58 if f < 0 { 59 return 0, errors.New("math: square root of negative number") 60 } 61 // implementation 62 return 0, nil // OMIT 63 } 64 65 // STOP OMIT 66 67 func printErr() (int, error) { // OMIT 68 f, err := Sqrt(-1) 69 if err != nil { 70 fmt.Println(err) 71 } 72 // STOP OMIT 73 // fmtError OMIT 74 if f < 0 { 75 return 0, fmt.Errorf("math: square root of negative number %g", f) 76 } 77 // STOP OMIT 78 return 0, nil 79 } 80 81 type NegativeSqrtError float64 82 83 func (f NegativeSqrtError) Error() string { 84 return fmt.Sprintf("math: square root of negative number %g", float64(f)) 85 } 86 87 // STOP OMIT 88 89 type SyntaxError struct { 90 msg string // description of error 91 Offset int64 // error occurred after reading Offset bytes 92 } 93 94 func (e *SyntaxError) Error() string { return e.msg } 95 96 // STOP OMIT 97 98 func decodeError(dec *json.Decoder, val struct{}) error { // OMIT 99 var f os.FileInfo // OMIT 100 if err := dec.Decode(&val); err != nil { 101 if serr, ok := err.(*json.SyntaxError); ok { 102 line, col := findLine(f, serr.Offset) 103 return fmt.Errorf("%s:%d:%d: %v", f.Name(), line, col, err) 104 } 105 return err 106 } 107 // STOP OMIT 108 return nil 109 } 110 111 func findLine(os.FileInfo, int64) (int, int) { 112 // place holder; no need to run 113 return 0, 0 114 } 115 116 func netError(err error) { // OMIT 117 for { // OMIT 118 if nerr, ok := err.(net.Error); ok && nerr.Temporary() { 119 time.Sleep(1e9) 120 continue 121 } 122 if err != nil { 123 log.Fatal(err) 124 } 125 // STOP OMIT 126 } 127 } 128 129 func main() {}